如果我想强制用户派生接口来实现私有方法/属性,有什么技巧吗?

发布于 2024-10-06 12:37:25 字数 387 浏览 5 评论 0原文

如果我想强制用户派生接口来实现私有方法,有什么技巧吗?

似乎我应该能够做一些事情来达到以下效果:

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

我明白为什么这不起作用,接口毕竟是从它派生的对象的有保证的公共前端,但是,必须有一种方法来强制实现我的接口的编码人员必须私下实现设置器。

在这种情况下抽象类可以工作吗?我不想定义代码,只是强制实现我的接口的人实现属性的私有设置器。

编辑: 是的,这是 C# :-)

If I want to force 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# :-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无名指的心愿 2024-10-13 12:37:25

您无法控制该属性的实施。时期。强迫他们将 setter 设为私有是没有意义的,接口的使用者都无法调用它。声明一个没人能调用的 setter 是没有意义的,最好省略它。现在它确实工作了,没有setter可以调用。这非常私密。

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.

世界和平 2024-10-13 12:37:25

使用抽象基类而不是接口:

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

Use an abstract base class instead of an interface:

public abstract class Foo
{
    public abstract int MyProperty { get; protected set; }
}
独行侠 2024-10-13 12:37:25

如果它是私有的,那么您似乎真正感兴趣的是控制一些公司内部的代码编写约定或类似的东西。也许您真正想要查看的是版本控制软件中的某些内容,该软件会拒绝不遵守规则的提交?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文