日期:2014-05-17  浏览次数:20740 次

如何给接口添加方法?
定义了一个接口,它的方法每个实现类都要写一遍,太麻烦。但是接口不能定义方法,用抽象类不能多继承?

怎么写比较简便?

------解决方案--------------------
本帖最后由 caozhy 于 2013-09-08 22:26:59 编辑
C# 3.0提供了扩展方法,可以优雅地解决这个问题:

interface Ixxx
{
    ...
}

static class IxxxHelper
{
    public static void CommonMethod(this IxxxHelper instance)
    {
       ...
    }
}

class A : Ixxx
{
    public void foo() { (this as Ixxx).CommonMethod(); }
}