有没有办法为C#接口创建默认属性实现

时间:2010-07-29 23:37:10

标签: c# properties methods interface

我喜欢为接口创建扩展方法以提供默认功能的技术。其中一个非常方便的地方就是在虚拟课上加点肉食进行单元测试。

例如,

public interface IEmployee
{
    IAddress Address { get; set; }

    IAddress GetAddress();
    void SetAddress(IAddress address);
}

public class Employee : IEmployee
{
    // Complex production stuff here (causes DB access)
}

public class TestEmployee : IEmployee
{
    // Simple unit testing stuff goes here (in memory only)
}

public static class EmployeeExtensions
{
    public static IAddress GetAddress(this IEmployee employee)
    {
        // Some sort of magic (maybe using IOC)
        // 'employee' can be either of type 'Employee' or of type 'TestEmployee'
    }

    public static void SetAddress(this IEmployee employee, IAddress address)
    {
        // Again with the magic
    }
}

好吧,也许不是一个很好的例子,但你明白了......

关键是可以针对Employee和TestEmployee调用GetAddress和SetAddress,而无需其中任何一个的代码支持。不幸的是,这感觉有点像Java而不是C#。我真正喜欢为两者做的是直接使用Address属性并使它具有与方法相同的魔力。我想避免的是必须在具体类中编写代码才能完成它(特别是在TestEmployee中)。

有没有办法为IEmployee的Address属性提供默认实现?

我知道C#属性实际上是方法。无论如何以某种方式为那些提供实现?

可以用不同的.NET语言完成吗?

2 个答案:

答案 0 :(得分:0)

正如您已经发现的那样,您无法通过扩展方法添加属性。如果这是一个缓和测试的问题,你可以使用像Moq这样的模拟框架来避免在从接口继承的每个类上实现这些属性。

答案 1 :(得分:0)

我想,有很多方法可以做到这一点。正如所建议的那样,您可以只考虑创建一个层次结构,以便这些类型的函数由基类处理。

但是,您可能对使用T4 Templates(来自Microsoft)的代码生成解决方案感兴趣。