C# 使用委托参数通过反射调用泛型方法时的问题
我已经胡闹了一个多小时了,只是似乎不能把它弄对。以下是我得到的一个例外: 错误:C# 使用委托参数通过反射调用泛型方法时的问题,c#,generics,reflection,delegates,C#,Generics,Reflection,Delegates,我已经胡闹了一个多小时了,只是似乎不能把它弄对。以下是我得到的一个例外: 错误:System.Func1[System.Object]类型的对象不能被删除 已转换为类型System.Func1[System.Collections.Generic.IEnumerable1[System.Collections.Generic.IEnumerable1[System.Object]]] 基本上我有一个通用的工厂方法,看起来像这样 ReturnItem<TResult> CreateOu
System.Func1[System.Object]
类型的对象不能被删除
已转换为类型System.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
参数?我通过将KeyValuePair的返回值更改为:
public KeyValuePair<Type, Type> CreateReturnInference()
{
return this is NormalOutputFactory
? new KeyValuePair<Type, Type>(typeof (object), typeof (object))
: new KeyValuePair<Type, Type>(typeof (IEnumerable<object>), typeof (object));
}
public KeyValuePair createReturn推断()
{
返回这是NormalOutputFactory
?新的KeyValuePair(类型(对象),类型(对象))
:新的KeyValuePair(typeof(IEnumerable)、typeof(object));
}
仍然不太乐意这样做,但解决了问题问题在于没有正确指定
Func
参数。换句话说,传递给CreateOutput
方法的内容类型不正确。当您这样做时:
MakeGenericMethod(infer.Key, infer.Value)
方法的类型参数
ReturnItem<TResult> CreateOutput<T, TResult>(Func<IEnumerable<T>> postBack, ...)
因此,您尝试创建的CreateOutput
方法具有如下签名:
ReturnItem<Enum> CreateOutput(Func<IEnumerable<IEnumerable<object>>> postBack, ...)
您的解决方案是:
1) 更改回调的签名如下:
Func<object> callBack = () => subTypes;
Func<IEnumerable<IEnumerable<object>>> callBack = () => subTypes;
Func callBack=()=>子类型;
2) 或者通过调整键值对函数来更改泛型方法的参数化类型
Func<IEnumerable<object>> callBack = () => subTypes;
public KeyValuePair<Type, Type> CreateReturnInference()
{
return ... new KeyValuePair<Type, Type>(typeof(object), typeof(Enum));
}
Func callBack=()=>子类型;
公钥值对CreateReturnExpression()
{
return…新的KeyValuePair(typeof(object),typeof(Enum));
}
我认为第二个是您想要的,但我不能确定。或者您甚至可以让CreateOutput方法接受“Func”作为参数,并相应地更改callback和CreateReturn推断。是的,您是正确的。我通过调整返回键对的方法对其进行排序。不过我有一个有趣的想法:假设我有一个对象,由这样一个抽象引用持有:IEnumerable@William我不确定我是否明白你的意思。是的,您可以转换IEnumerable
Func<object> callBack = () => subTypes;
Func<IEnumerable<IEnumerable<object>>> callBack = () => subTypes;
Func<IEnumerable<object>> callBack = () => subTypes;
public KeyValuePair<Type, Type> CreateReturnInference()
{
return ... new KeyValuePair<Type, Type>(typeof(object), typeof(Enum));
}