如果只能在运行时推断出类型,那么如何使用反射来执行以下方法?
MainObject.TheMethod<T>(Action<OtherObject<T>>)
在日常使用中,通常是:
mainObject.Method<Message>(m => m.Do("Something"))
因此,给定一个类型列表,我需要在上面的方法中将它们替换为T并调用。
这是我在头脑中转向腻子的地方:
var mapped = typeof(Action<OtherObject<>>).MakeGenericType(t.GetType());
Activator.CreateInstance(mapped, new object[] { erm do something?});
typeof(OtherObject)
.GetMethod("TheMethod")
.MakeGenericMethod(t.GetType())
.Invoke(model, new object[] { new mapped(m => m.Do("Something")) });
更新:为了澄清,我有一个类型列表,我希望为每个类型执行相同的已知OtherObject方法。伪代码:
foreach(var t in types)
{
mainObject.TheMethod<t>(mo => mo.Do("Something"))
}
(TheMethod()的参数类型为Action<OtherObject<T>>
,如上所述)
FluentNHibernate.Automapping.AutoPersistenceModel Override<T>(System.Action<AutoMapping<T>> populateMap)
此操作与AutoMapping<T>.Where("something")
model.Override<Message>(m => m.Where("DeletedById is null"))
现在,针对一堆类型执行此操作:)
答案 0 :(得分:3)
您可以使用表达式解决此问题:
foreach(var t in types)
{
var mapped = typeof(AutoMapping<>).MakeGenericType(t);
var p = Expression.Parameter(mapped, "m");
var expression = Expression.Lambda(Expression.GetActionType(mapped),
Expression.Call(p, mapped.GetMethod("Do"),
Expression.Constant("Something")), p);
typeof(SomeOtherObject).GetMethod("TheMethod").MakeGenericMethod(t)
.Invoke(model, new object[] { expression.Compile() });
}
更新:完成工作示例(粘贴到LINQPad并运行它):
void Main()
{
var types = new []{typeof(string), typeof(Guid)};
SomeOtherObject model = new SomeOtherObject();
foreach(var t in types)
{
var mapped = typeof(AutoMapping<>).MakeGenericType(t);
var p = Expression.Parameter(mapped, "m");
var expression = Expression.Lambda(
Expression.GetActionType(mapped),
Expression.Call(p, mapped.GetMethod("Do"),
Expression.Constant("Something")), p);
typeof(SomeOtherObject).GetMethod("TheMethod")
.MakeGenericMethod(t)
.Invoke(model,
new object[] { expression.Compile() });
}
}
class AutoMapping<T>
{
public void Do(string p)
{
Console.WriteLine(typeof(T).ToString());
Console.WriteLine(p);
}
}
class SomeOtherObject
{
public void TheMethod<T>(Action<AutoMapping<T>> action)
{
var x = new AutoMapping<T>();
action(x);
}
}