c# - 扩展类以符合接口(interface)?

标签 c# interface extension-methods

我有一个界面:

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/

相关文章:

C#:验证扩展方法中的 "this"参数的最佳实践

c# - 序列化已知的小结构数组的好方法

c# - 如何在 dotnet core 2.1 中使用 256 长 block 大小的 Rijndael 算法

inheritance - 如何检测对象中分配给 Dart 基类变量的接口(interface)?

java - 关于接口(interface)引用变量的问题

带有形状体积和面积类的 Java 接口(interface)

c# - IEnumerable<T> 是否替换了糟糕的设计?

ruby - 覆盖方法然后还原

c# - 数据绑定(bind)到最初为空的对象

c# - 将界面解析为 UIElement(Unity、PRISM、C#)