c# - 实现通用接口(interface)方法的方法中的专用类型

标签 c# generics

我在接口(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/

相关文章:

c# - 从 DateTime c# 中的 Ticks 获取毫秒数

c# - 静态一次性元素

ios - 快速在通用类中实现协议(protocol)

c# - 通用方法和无效上下文异常

c# - 从 10 位数字中获取所有可能的连续 4 位数字

c# - 通过查询字符串传递 Int 类型值

c# - 从同步执行中获取任务结果

c# - 接受多种类型的方法参数

entity-framework - 使用通用存储库是一种好习惯还是每个实体都应该拥有自己的存储库?

linq - where 子句的通用表达式 - "The LINQ expression node type ' Invoke' 在 LINQ to Entities 中不受支持。”