我已经花了一个多小时来解决这个问题,但似乎无法正确解决。这是我遇到的例外之一:
错误:类型的对象
System.Func1[System.Object]
无法转换为typeSystem.Func1[System.Collections.Generic.IEnumerable1[System.Collections.Generic.IEnumerable1[System.Object]]]
。
基本上我有一个通用的工厂方法,看起来像这样
ReturnItem<TResult> CreateOutput<T, TResult>(Func<IEnumerable<T>> postBack,
Processor manager) where TResult : class;
并且我正在尝试反思,但是这Func<IEnumerable<T>>
导致了我的问题。这是我尝试调用的代码:
var infer = Factory.CreateReturnInference(); //Keypair value (type, type) is NOT an NormalOutputFactory in this instance
Func<object> callBack = () => subTypes;
var toRun = Factory.GetType()
.GetMethod("CreateOutput", BindingFlags.Public | BindingFlags.Instance)
.MakeGenericMethod(infer.Key, infer.Value)
.Invoke(Factory,
new object[] {callBack, Manager}) as
ReturnItem<object>;
从中返回的密钥对值Factory.CreateReturnInference
用于指定通用参数,仅用于提供其实现的清晰性(警告非常丑陋的代码,违反了其他交易标准:)
public KeyValuePair<Type, Type> CreateReturnInference()
{
return this is NormalOutputFactory
? new KeyValuePair<Type, Type>(typeof (object), typeof (Log))
: new KeyValuePair<Type, Type>(typeof (IEnumerable<object>), typeof (Enum));
}
一般的问题是:通过反射调用泛型方法时,如何指定Func
参数?
问题是您没有Func<T>
正确指定参数。换句话说,您要传递给CreateOutput
方法的是错误的类型。当您这样做时:
MakeGenericMethod(infer.Key, infer.Value)
方法的类型参数
ReturnItem<TResult> CreateOutput<T, TResult>(Func<IEnumerable<T>> postBack, ...)
您正在通过aretypeof(IEnumerable<object>)
和typeof(Enum)
。因为你做
return new newKeyValuePair<Type, Type>(typeof(IEnumerable<object>), typeof(Enum));
因此,CreateOutput
您尝试创建的方法具有如下签名:
ReturnItem<Enum> CreateOutput(Func<IEnumerable<IEnumerable<object>>> postBack, ...)
换句话说,T
成为IEnumerable<object>
和TResult
成为Enum
。但是Func
您传递来调用构造的泛型方法的参数的callback
定义如下:
Func<object> callBack = () => subTypes;
1)更改签名callback
如下:
Func<IEnumerable<IEnumerable<object>>> callBack = () => subTypes;
2)或通过调整键值对函数来更改通用方法的参数类型。
Func<IEnumerable<object>> callBack = () => subTypes;
public KeyValuePair<Type, Type> CreateReturnInference()
{
return ... new KeyValuePair<Type, Type>(typeof(object), typeof(Enum));
}
我认为第二个是您想要的,但是我不确定。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句