在 c# 中在父接口中声明属性 getter,在子接口中声明 setter

  • 本文关键字:接口 声明 setter getter 属性 c#
  • 更新时间 :
  • 英文 :


我想在父接口中声明属性的getter和子接口中的setter

public interface IReadOnlyValue
{
int Value { get; }
}
public interface IValue : IReadOnlyValue
{
int Value { set; }
}
public class Value : IValue 
{
int Value { get; set; }
}

不会编译,因为来自IValuehidesValue来自IReadOnlyValue的。有没有办法做到这一点,知道我需要Value才能成为财产

似乎这是一个类名Value这是错误的:

错误 CS0542"值":成员名称不能与其名称相同封闭型

(粗体是我的(。如果您将Value重命名为,例如,MyValue

就可以了:
public interface IReadOnlyValue {
int Value { get; }
}
// It seems that IValue should have both "get" and "set"
// See IList<T> and IReadOnlyList<T> as an example
// However, you can drop "get" if you want
public interface IValue {
int Value { get; set; }
}
public class MyValue: IReadOnlyValue, IValue {
public int Value { get; set; }
}

最新更新