代码片段无法编译,因为它只是为了展示我想要实现的目标: 说我有一个界面:
public Interface IWalker
{
//Compiles but not what I need
double DistanceTravelled {get; set;}
//Compiler error - cant be private for set, but that's what I need
//double DistanceTravelled {get; private set;}
}
public abstract AbstractWalker : IWalker
{
//Error:Cannot implement - but thats what I need
//protected double DistanceTravelled {get; private set}
//Error the set is not public and I dont want the property to be public
//public double DistanceTravelled { get;private set; }
//Compiles but not what i need at all since I want a protected
// property -a. and have it behave as readonly - b. but
// need it to be a part of the interface -c.
public double DistanceTravlled {get; set;}
}
我所有具体的AbstractWalker实例实际上都是IWalker的类型。 实现我在代码段中指定的设计的最佳方法是什么?
答案 0 :(得分:10)
如果你想要私人套装,只需在界面中指定一个get:
public interface IWalker
{
double DistanceTravelled {get; }
}
然后,IWalker的实施者可以指定私有集:
public class Walker : IWalker
{
public double DistanceTravelled { get; private set;}
}
答案 1 :(得分:0)
您的设计存在缺陷。接口用于描述API的“公共合同”,因此您希望(a)私有设置器和(b)受保护的实现非常奇怪。
如果您需要更多帮助,则必须提供有关设计的更多信息。