![](/img/trans.png)
[英]Assembly.CreateInstance(): how to enforce Interface implementation
[英]How to make the interface enforce the implementation not having a setter?
遵循示例:
interface ISomeInterface
{
string SomeProperty { get; }
}
我有编译的实现:
public class SomeClass : ISomeInterface
{
public string SomeProperty
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
这是一个问题。 我如何使接口成为合同,不允许在其实现中设置?
注意:我不是要寻找一种避免在实现中设置set的解决方案,而是在一个可以从任何新实现中对其进行验证的界面中,谢谢。
接口仅指定必须实现的内容,而不限制其他可以实现的方法或属性。
因此,get是您指定的唯一内容。
由于您对集合保持沉默,因此接口的任何实现者都可以随意添加或不添加集合。
简而言之,使用接口规范,您无法做自己想做的事情。
如果要确保从未调用过该集合,则可以始终将实例强制转换为接口
如果您确实需要确保没有设置,可以使用抽象类代替接口
abstract class SomeInterface
{
virtual string SomeProperty { get; }
}
根据Mike的回答,您可以这样写:
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(将接口作为具体的类进行处理)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.