开发者

If I want to force users deriving an Interface to implement a private method/property, is there some trick?

If I want to f开发者_如何学Pythonorce users deriving an Interface to implement a private method, is there some trick?

It seems as though I should be able to do something to the effect of:

namespace cc
{
    interface Icd
    {
        int one { get; private set; }
        int two { get; private set; }
    }
}

I understand why this won't work, an interface after all is the guaranteed public front end for objects derived from it, however, there must be a way to force coders implementing my interface to have to implement the setter privately.

Would an abstract class work in this case? I don't want to define code, just force whoever implements my interface to implement a private setter for properties.

Edit: Yes, this is C# :-)


You cannot control the implementation of the property. Period. Forcing them to make the setter private doesn't make sense, no consumer of the interface could ever call it. No point in declaring a setter that nobody can call anyway, might as well omit it. Now it does work, there is no setter to call. That's pretty private.


Use an abstract base class instead of an interface:

public abstract class Foo
{
    public abstract int MyProperty { get; protected set; }
}


If it's private, it seems like what you're really interested in controlling is some intra-company code-writing conventions or something like that. Maybe what you really want to be looking at is something from your version control software that would reject commits that don't follow the rules?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜