将从Reflection获得的类传递给泛型方法

时间:2012-08-09 16:36:33

标签: c# generics reflection

这是我想要做的一个虚拟示例:

var ass = Assembly.Load("Dummy.Class.FullName");

var yy =
    from t in ass.GetTypes()
    let attributes = t.GetCustomAttributes(typeof(MyTestAttribute), true)
    where attributes != null && attributes.Length > 0
    select new { Type = t, Attributes = attributes.Cast<MyTestAttribute>() };

foreach (var x in yy)
{
    TestOpen<typeof(x.Type)>();
}

private void TestOpen<TEntity>() where TEntity : Entity, new()
{
}

我无法获得类定义并以这种方式传递给泛型方法,我尝试了所有方法,我想我错过了一些特殊的方法,即方法正在等待一些编译类和反射我无法得到这个,正确的吗?

欢呼声

1 个答案:

答案 0 :(得分:1)

您可以使用MakeGenericMethod生成正确的方法定义,并通过反射调用它。

Type thisType = this.GetType();

var mi = thisType.GetMethod("TestOpen");

foreach (var x in yy)
{
    var gmi = mi.MakeGenericMethod(x.Type);
    gmi.Invoke(this, null);
}