如何使接口强制执行没有资源库的实现

本文关键字:资源库 实现 何使 接口 强制执行 | 更新日期: 2023-09-27 18:30:50

以下示例:

interface ISomeInterface
{
    string SomeProperty { get; }
}

我有编译的实现:

public class SomeClass : ISomeInterface
{
    public string SomeProperty
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
 }

这是一个问题。如何使接口成为不允许在其实现中设置的合约?

注意:我不是在寻找如何避免在实现中设置的解决方案,而是在将从任何新实现中验证它的界面中,谢谢。

如何使接口强制执行没有资源库的实现

接口只指定必须实现的内容,但不限制还可以实现的其他方法或属性。

因此,get是您指定的唯一内容。

由于您在集合上保持沉默,因此接口的任何实现者都可以自由添加或不添加集合。

简而言之,使用接口规范,您无法执行要执行的操作。

如果要确保永远不会调用集合,则始终可以将实例强制转换为接口

如果你真的需要确保没有集合,你可以使用抽象类而不是接口

abstract class SomeInterface
{
   virtual string SomeProperty { get; }
}

基于迈克的回答,你可以写这样的东西:

public interface ISomeInterface
{
    string SomeProperty { get; }
}
public abstract class SomeInterfaceBase : ISomeInterface
{
    public abstract string SomeProperty { get; }
}

因此,您可以像这样定义类:

public class SomeClass : SomeInterfaceBase
{
    public override string SomeProperty { get; }
}

如果你尝试实现一个setter,它将无法编译。

拥有二传手不是问题。其原因是因为我们对待接口的方式。

具体类是否有 setter 并不重要,因为我们应该将对象视为 ISomeInterface。在这种情况下,它只有一个二传手。

例如,让我们采用一个工厂方法:

class Program
{
    interface ISomeInterface
    {
        string SomeProperty { get; }
    }
    static ISomeInterface CreateSomeClass()
    {
        return new SomeClass();
    }
    class SomeClass : ISomeInterface
    {
        public string SomeProperty
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    }
    static void Main(string[] args)
    {
        ISomeInterface someInterface = CreateSomeClass();
        someInterface.SomeProperty = "test"; //Wont compile
    }
}

类对 setter 的实现是没有意义的,因为我们只对将对象视为 ISomeInterface 感兴趣。接口是累加的。换句话说,它们定义了需要定义什么的合同,而不是不应该定义什么。

如果我以任何其他方式对待它,它将是这样的:

    ((SomeClass) someInterface).SomeProperty = "test"; //Code smell

我会认为这是一种代码气味,因为它假设 someInterface 是 SomeClass(将接口视为具体类)