繁体   English   中英

将从Reflection获得的类传递给通用方法

[英]Pass a class gotten from Reflection to a generic method

这是我要尝试的一个虚拟示例:

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()
{
}

我无法获得类定义并以这种方式传递给通用方法,我尝试了一切,我想我特别想念了一些方法,该方法正在等待某个编译的类,并且从反思的角度来看,我不能得到它,对吗?

干杯

您可以使用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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM