C#7
我是泛型新手。我该如何解决?
在objO = SetPatient(P)上,我得到:
P是在给定上下文中无效的类型。
我该如何解决?
TIA
public interface IOrderMaker
{
void SetPatient(IService p);
}
public class OrderMaker<O, P, T>
where O : class, IOrderMaker
where T : class, O, new()
where P : IService
{
public static O CreateInstance()
{
O objO;
objO = new T();
objO.SetPatient(P);
return objO;
}
}
答案 0 :(得分:2)
P
是通用参数类型,而不是变量。
您需要传递一个实际变量,而不是类型
public class OrderMaker<O, P, T>
where O : class, IOrderMaker
where T : class, O, new()
where P : IService
{
public static O CreateInstance(P p) { //<--
O objO = new T();
objO.SetPatient(p); //<---
return objO;
}
}
除此之外,这可能是XY problem,因为不清楚您最终要做什么。
答案 1 :(得分:1)
SetPatient
需要一个实现了 interface
void SetPatient(IService p);
但是,您是从通用类OrderMaker
objO.SetPatient(P);
P
此时只是附加到类的一小部分元数据。即使您可以将其传递给SetPatient
,除了知道类型之外,它也无能为力。在这种情况下,您也可以使其通用化