在C#中,接口属性的访问修饰符只能是public
public interface IMyInterface
{
// 公共属性
int MyProperty { get; set; }
}
在实现此接口的类中,你可以选择使用其他访问修饰符(如private、protected等),但这些修饰符仅适用于类内部。外部代码仍然可以通过接口访问这些属性,因为它们被视为public。
例如:
public class MyClass : IMyInterface
{
// 私有属性,仅在类内部可访问
private int _myProperty;
// 实现接口属性,但使用私有字段
public int MyProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}
}
在这个例子中,MyClass实现了IMyInterface接口,并将MyProperty属性设置为私有。然而,外部代码仍然可以通过IMyInterface接口访问MyProperty属性,因为它被视为public。