将类型参数传递给泛型类

时间:2018-06-21 13:26:59

标签: c# generics reflection

我需要将类型作为参数传递给泛型类。我正在尝试从类型列表中获取类型。示例:

 void Main()
{
    var test = new Test();
    test.testMethod();
}

public static class ListClass<T>
{
   public static bool getValues()
   {
       return true;
   }
}

public class X { public int a; public int b; }

public class Y { public string s; public float f; }

class Test
{
    List<Type> listType = new List<Type>();

    public Test()
    {
       listType.Add(typeof(X));
       listType.Add(typeof(Y));
    }

    public void testMethod()
    {
       Console.WriteLine(ListClass<X>.getValues());
       Console.WriteLine(ListClass<Y>.getValues());
    }
}

我想循环通话,而不是在每一行都通话。

1 个答案:

答案 0 :(得分:0)

为了论证,让我们假设,根据我在评论中的要求,您在问题中发布的代码是:

void Main()
{
    var test = new Test();
    test.testMethod();
}

public static class ListClass<T>
{
    public static bool getValues()
    {
        return true;
    }
}

public class X { public int a; public int b; }

public class Y { public string s; public float f; }

class Test
{
    List<Type> listType = new List<Type>();

    public Test()
    {
        listType.Add(typeof(X));
        listType.Add(typeof(Y));
    }

    public void testMethod()
    {
        Console.WriteLine(ListClass<X>.getValues());
        Console.WriteLine(ListClass<Y>.getValues());
    }
}

基本上就是可以编译并运行的代码。现在,您想知道如何实际运行此非法代码:

public void testMethod()
{
    foreach (var type in listType)
    {
        Console.WriteLine(ListClass<type>.getValues());
    }
}

方法如下:

public void testMethod()
{
    foreach (var type in listType)
    {
        Console.WriteLine(
            (bool)typeof(ListClass<>)
                .MakeGenericType(type)
                .GetMethod("getValues")
                .Invoke(null, new object[] { }));
    }
}

现在,我不知道这是否是您需要的代码,因为您没有发布我所要求的示例。不过,我希望这会有所帮助。