我在接口(interface)中有一个方法,我想在实现该接口(interface)的类中专门化其类型。像这样的事情:
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 上放置一个类型参数并让它进行编译,但这会变得困惑,所以我想知道是否有某种方法可以在没有它的情况下做到这一点。有没有某种方法可以仅通过接口(interface)和类中方法的声明来实现,这样我就可以让子类使用它自己的类型,但在接口(interface)中声明它?
最佳答案
抱歉,但向 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;
}
}
在我看来,它看起来不那么困惑。
已更新
我在不需要类型参数的地方添加了一个不带泛型类型参数的基本 Iface
接口(interface)。
关于c# - 实现通用接口(interface)方法的方法中的专用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32293414/