我读到自动实现的属性不能只读或只写。它们只能是可读写的。
但是,在学习界面时,我遇到了很多问题。代码,它创建一个只读/只写和读写类型的自动属性。这是可以接受的吗?
public interface IPointy
{
// A read-write property in an interface would look like:
// retType PropName { get; set; }
// while a write-only property in an interface would be:
// retType PropName { set; }
byte Points { get; }
}
最佳答案
这不是自动实现的。接口(interface)不包含实现。
声明接口(interface)IPointy
需要byte
类型的属性,名为Points
,带有公共(public)getter.
只要有public getter,你可以用任何必要的方式实现接口(interface);是否通过自动属性:
public class Foo: IPointy
{
public byte Points {get; set;}
}
注意 setter 仍然可以是私有(private)的:
public class Bar: IPointy
{
public byte Points {get; private set;}
}
或者,您可以显式编写一个 getter:
public class Baz: IPointy
{
private byte _points;
public byte Points
{
get { return _points; }
}
}
关于c# - 只读和只写接口(interface)中的自动属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30022654/