扩展一个类以符合接口?

时间:2013-10-13 02:41:28

标签: c# interface extension-methods

我有一个界面:

interface IFoo {
  int foo(int bar);
}

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

2 个答案:

答案 0 :(得分: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) {}
}

当类被密封时,你唯一的解决方案是将它作为一个接口通过组合呈现:编写一个实现你的接口的包装类,给它一个密封类的实例,并编写方法实现“转发”调用包装目标类的实例。

答案 1 :(得分:1)

我认为这个问题可以重申为“我可以使用扩展方法来创建一个密封的类实现一个之前没有的接口吗?”正如其他人指出的那样,String类是密封的。但是,我认为你必须说明一个类在其声明中实现的接口:

public someClass : IFoo
{
    // code goes here
}

所以你不能直接对String这样做,不仅因为它是密封的,而且因为你没有它的源代码。

你能做的最好的事情就是让自己的类具有一个String并像字符串一样使用它。你需要做的任何String你需要做的就是它的String成员(因此公开),或者你必须包装/重新实现你需要的方法:

public class betterString : IFoo
{
   public String str {get; set;}

   public foo(int i)
   {
      // implement foo
   }
}

然后,在使用它时:

public void someMethod(betterString better)
{
   better.foo(77);
   System.Console.WriteLine(better.str);
}