我有点困惑。我想创建一个名为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/