简体   繁体   English

在实现通用接口方法的方法中专门化类型

[英]Specialize type in method that implements a generic interface method

I have a method in an interface that I want to specialize the types for in classes that implement that interface. 我在接口中有一个方法,想要对实现该接口的类的类型进行专门化处理。 Something like this: 像这样:

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;
    }
}

This doesn't compile of course. 这当然不能编译。 I know I could put a type param on Iface and get it to compile, but that gets messy and so I'm wondering if there is some way to do it without that. 我知道我可以在Iface上放一个类型参数,然后将其编译,但这很乱,所以我想知道是否有某种方法可以做到这一点。 Is there some way just from the declarations of the methods in the interface and class that can make it so I can have the subclass work with it's own type but declare it in the interface? 从接口和类中方法的声明中是否有某种方法可以使之实现,因此我可以让子类使用其自己的类型,但可以在接口中进行声明?

Sorry, but adding a type param to the Iface is the only way that I think that you can do this. 抱歉,但是向Iface添加类型参数是我认为可以执行此操作的唯一方法。 Why do you think it is messy? 您为什么认为它很乱?

Here it is: 这里是:

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;
    }
}

It looks less messy to me. 在我看来,它看起来不那么混乱。

Updated 更新

I added a base Iface interface without the generics type parameter for the places where the type parameter is not needed. 我为不需要type参数的位置添加了一个基本的Iface接口,但没有泛型type参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM