泛型类中的非泛型方法调用显示“类型无效”

时间:2019-04-12 02:57:14

标签: c# generics

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;
    }
}

2 个答案:

答案 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

instantiated 类。
void SetPatient(IService p);

但是,您是从通用类OrderMaker

给它一个通用参数的
objO.SetPatient(P);

P此时只是附加到类的一小部分元数据。即使您可以将其传递给SetPatient,除了知道类型之外,它也无能为力。在这种情况下,您也可以使其通用化