这是一个加载的问题,或许通过一个例子更有意义。
我已经尝试过这样做,所以我通常可以拥有两个版本的类,只读和不可变,带有接口。
public interface IReadableX
{
// string is already immutable, great.
string A { get; }
}
public class ReadOnlyX : IReadableX
{
public string A { get; }
}
public class MutableX : IReadableX
{
public string A { get; set;}
}
但现在我想要另一个包含IReadableX
的类:
public interface IReadableY
{
IReadableX X {get;}
}
public class ReadOnlyY : IReadableY
{
public ReadOnlyX X {get;}
}
public class MutableY : IReadableY
{
public MutableX X { get; set;}
}
这一切看起来都很好,直到上面的编译都无法编译,因为这些属性与IReadableY
属性的返回类型不匹配(即使它们是派生的)。 )The fiddle is here。
如何通过我想要的保证实现我想要的界面?
我考虑的另一种可能性是:
public interface IReadableY
{
IReadableX X {get;}
}
public class ReadOnlyY : IReadableY
{
public IReadableX X {get;}
}
public class MutableY : IReadableY
{
public IReadableX X { get; set;}
}
但是当有人看到ReadOnlyY
时,它并不是很明显,因为它不清楚属性X
是否只会被允许设置为ReadOnlyX
。