C# 将泛型参数lambda委托转换为对象
我有以下方法:C# 将泛型参数lambda委托转换为对象,c#,generics,lambda,delegates,C#,Generics,Lambda,Delegates,我有以下方法: void Foo<T1>(Func<T1, Exception> exceptionFunc) { // Following line error: "Cannot convert from 'object' to 'T1' Func<object, Exception> exF = (e) => exceptionFunc(e); Foo2(exF); } void Foo(Func exceptionFunc) {
void Foo<T1>(Func<T1, Exception> exceptionFunc)
{
// Following line error: "Cannot convert from 'object' to 'T1'
Func<object, Exception> exF = (e) => exceptionFunc(e);
Foo2(exF);
}
void Foo(Func exceptionFunc)
{
//以下行错误:“无法从“对象”转换为“T1”
Func exF=(e)=>exceptionFunc(e);
Foo2(exF);
}
我似乎不知道如何将
Func
的泛型参数T1
强制转换为Foo2()
所需的对象,有没有办法成功执行此操作?必须将对象转换为T1:
void Foo<T1>(Func<T1, Exception> exceptionFunc)
{
// Following line error: "Cannot convert from 'object' to 'T1'
Func<object, Exception> exF = obj => exceptionFunc((T1)obj);
Foo2(exF);
}
void Foo(Func exceptionFunc)
{
//以下行错误:“无法从“对象”转换为“T1”
Func exF=obj=>exceptionFunc((T1)obj);
Foo2(exF);
}
注意:如果对象与T1不兼容,则会在运行时引发无效的强制转换异常。Func exF=(e)=>exceptionFunc((T1)e)代码>?我尝试了Func exF=obj=>exceptionFunc((object)obj)
之前的演员阵容当然是错误的。谢谢