在实现通用接口方法的方法中使用Specialize类型

时间:2015-08-30 05:16:58

标签: c# generics

我在接口中有一个方法,我想在实现该接口的类中专门化类型。像这样:

public interface Iface
{
    Function<Some, Some> Updater<T>(Func<T, T> op) where T : Iface;
}

public class Test : Iface
{
    public Function<Some, Some> Updater<T>(Func<T, T> op) where T : Test
    {
        // Use op with parameters that are of type Test
        return null;
    }
}

当然,这不是编译。我知道我可以在Iface上放一个类型的参数并让它进行编译,但是这会变得混乱,所以我想知道如果没有它就有办法做到这一点。是否有一些方法可以从接口和类中的方法声明中获得它,这样我可以让子类使用它自己的类型但在接口中声明它?

1 个答案:

答案 0 :(得分:1)

很抱歉,但是向Iface添加类型参数是我认为您可以执行此操作的唯一方法。为什么你觉得它很乱?

这是:

public interface Iface
{
    // TODO: Add non type specific methods here
}

public interface Iface<TIface> : Iface
    where TIface : Iface<TIface>
{
    // Type specific methods get defined here
    Function<Some, Some> Updater(Func<TIface, TIface> op);
}

public class Test : Iface<Test> // <- We're implementing the generic version of Iface<TIface> instead of Iface.  Note that Iface<TIface> extends Iface, so this class must implement that interface too.
{
    public Function<Some, Some> Updater(Func<Test, Test> op)
    {
        // Use op with parameters that are of type Test
        return null;
    }
}

对我来说看起来不那么混乱。

<强>更新

我为不需要type参数的地方添加了一个没有generics类型参数的基本Iface接口。

相关问题