c# - 具有泛型类型的抽象方法

标签 c# .net

我正在努力做到这一点: My model

我有点困惑。我想创建一个名为Update(T other) 的函数,参数“other”类型是类类型。我认为,使用在抽象类中实现的通用接口(interface),它会起作用,但它不起作用。 :/

如何获得带有泛型类型参数的抽象方法,并在继承的类中指定该类型?那可能吗?我的方法正确吗?

代码:

public interface IUpdateable<T>
{
    void Update(T pOther);
}

public abstract class Instruction_Template : IUpdateable<Instruction_Template>
{
    public abstract void Update(??? pOther);
}

public class Work_Instruction_Template : Instruction_Template
{
    public void Update(Work_Instruction_Template pOther)
    {
       //logic...
    }
}

谢谢!

最佳答案

使用 curiously recurring template pattern .

abstract class Instruction_TP<T> 
    where T : Instruction_TP<T>
{
    public abstract void Update(T instruction);
}

class Process_Instruction_TP : Instruction_TP<Process_Instruction_TP>
{
    public override void Update(Process_Instruction_TP instruction)
    {
        throw new NotImplementedException();
    }
}

abstract class NC_Instruction_TP<T> : Instruction_TP<T>
    where T : NC_Instruction_TP<T>
{ }

class Drill_Instruction_TP : NC_Instruction_TP<Drill_Instruction_TP>
{
    public override void Update(Drill_Instruction_TP instruction)
    {
        throw new NotImplementedException();
    }
}

关于c# - 具有泛型类型的抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36447162/

相关文章:

c# - 从 Winform 显示 HTML 文件

c# - 讽刺:没有 StartEndSymbol 的 StringLiteral

c# - 需要调试从客户端计算机请求的 Web API 服务 - 需要帮助,我该怎么做?

c# - 调用堆栈中的 "external code"是什么意思?

c# - 如何使用多线程处理大队列(临时文件?)

c# - Dapper 使用存储过程将多行插入到两个表中

c# - 两台服务器之间的高效文件读/写

c# - 如何从 Azure webjob 到 Azure webapp 进行通信?

c# - 无法在 C# 中验证多个 xsd 架构

c# - 如何从 Visual Studio 将可执行文件发布到我的 Azure Function?