gpt4 book ai didi

c# - 接口(interface)的私有(private)成员

转载 作者:行者123 更新时间:2023-11-30 13:22:25 25 4
gpt4 key购买 nike

如果在我的程序中我有接口(interface),那么它的所有成员都是隐含的public。在实现该接口(interface)的类中,我也必须使该成员(属性)public

有什么方法可以让它私有(private)吗?

最佳答案

Is it any way to make an interface implementation private?

不是完全私有(private)的——一个接口(interface)代表一组公共(public)的方法和属性。无法将接口(interface)实现设为私有(private)。

可以做的是使实现显式:

public interface IFoo
{
void Bar();
}

public class FooImpl
{
void IFoo.Bar()
{
Console.WriteLine("I am somewhat private.")
}

private void Bar()
{
Console.WriteLine("I am private.")
}

}

现在调用 IFoo.Bar() 的唯一方法是显式通过接口(interface):

FooImpl f = new FooImpl();
f.Bar(); // compiler error
((IFoo)f).Bar();

关于c# - 接口(interface)的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23545232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com