我有一个界面:
interface IFoo {
int foo(int bar);
}
我现在可以扩展现有类以符合接口(interface)吗?说类字符串。我知道我可以在字符串上定义 foo() 方法。但是是否可以更进一步,告诉编译器字符串可以转换为 IFoo?
最佳答案
您可以使用其他类,但不能使用 System.String
,因为它是密封的
。
如果您想对非密封类执行此操作,您可以简单地从它派生,添加适当的构造函数,并将接口(interface)作为您的新类实现的东西。
interface IFoo {
int Size {get;}
}
// This class already does what you need, but does not implement
// your interface of interest
class OldClass {
int Size {get;private set;}
public OldClass(int size) { Size = size; }
}
// Derive from the existing class, and implement the interface
class NewClass : OldClass, IFoo {
public NewCLass(int size) : base(size) {}
}
当类被密封时,通过组合将其呈现为某个接口(interface)的唯一解决方案是:编写一个实现接口(interface)的包装类,为其提供一个密封类的实例,然后编写“转发”调用包装类的方法实现目标类的实例。
关于c# - 扩展类以符合接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341289/