扩展类以符合接口?

Wil*_*sch 5 c# extension-methods interface

我有一个界面:

interface IFoo {
  int foo(int bar);
}
Run Code Online (Sandbox Code Playgroud)

我现在可以扩展现有的类以符合该接口吗?说出String类。我知道我可以在字符串上定义foo()方法。但是是否可以进一步告诉编译器可以将字符串强制转换为IFoo?

das*_*ght 6

您可以使用其他类,但不能使用System.String它,因为它是sealed

如果您想对非密封类执行此操作,则可以简单地从其派生,添加适当的构造函数并将接口作为您的新类实现的对象。

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) {}
}
Run Code Online (Sandbox Code Playgroud)

当密封该类时,您唯一的解决方案是通过组合将其表示为某些接口:编写实现您的接口的包装器类,为其提供密封类的实例,并编写“转发”调用包装类实例的方法实现。目标阶层。

  • 令人失望的是,这是公认的答案,因为这显示了子类化,而不是扩展类,这将使用类扩展。如果您使用扩展,您*可以*扩展 System.String,但我不确定您是否可以使用扩展来符合接口。 (2认同)