【问题标题】:Interfaces exposing generic overload. How to DRY here?暴露泛型重载的接口。如何在这里干燥?
【发布时间】:2015-08-31 18:45:50
【问题描述】:

我有这个界面

interface IMyInterface 
{
    object Create(Type t);
}

为方便起见,我还将包含一个通用重载,它包装了对该方法的调用,因此它变为:

interface IMyInterface 
{
    object Create(Type t);
    T Create<T>();
}

新方法会这样实现

public object Create<T>()  
{
    return (T) Create(typeof(T)); 
}

方法的问题:

  • 如果我在界面中包含重载,那么我正在强制 实现者有一个愚蠢的包装方法,它总是 一样。
  • 如果我不包含重载,则在使用对IMyInteface 的引用时将失去调用能力

我该如何解决这个设计问题?

【问题讨论】:

  • 改用抽象类
  • 抽象类可能是一个解决方案,但在这里不是一个选项。它会以另一种方式限制用户,这是我不想要的。
  • 为什么Create&lt;T&gt; 不返回T 而不是object
  • D 斯坦利:酷!编辑了问题。

标签: c# .net generics interface


【解决方案1】:

最好的解决方案是使用扩展方法:

public static MyInterfaceExtensions
{
    public T Create<T>(this IMyInterface target)  
    {
        return (T) target.Create(typeof(T)); 
    }
}

然后可以像常规方法一样调用扩展方法。

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多