我有点困惑。我想创建一个名为 Update(T other)的函数,参数“other”类型是类类型。我认为,通过在抽象类中实现的通用接口,它可以工作,但它不起作用。 :/
如何使用泛型类型参数获取抽象方法,并在继承的类中指定该类型?那可能吗?我的方法是否正确?
代码:
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...
}
}
谢谢!
答案 0 :(得分:2)
使用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();
}
}
答案 1 :(得分:2)
有什么问题?
public interface IstructionTP<T>
where T : class
{
void Update(T entity);
}
public class ProcessIstructionTP : IstructionTP<ProcessIstructionTP>
{
public void Update(ProcessIstructionTP entity)
{
...
}
}