本文介绍了T,T,T>不能从Func键<转换;到Func键< T,T,T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我挺这个错误困惑:
The types are identical, why is it even trying to do a cast? Here's the code:
public static class Operators<T>
{
private static Func<T,T,T> _add = null;
public static T Add<T>(T a, T b)
{
if (_add == null) {
var param1Expr = Expression.Parameter(typeof (T));
var param2Expr = Expression.Parameter(typeof (T));
var addExpr = Expression.Add(param1Expr, param2Expr);
var expr = Expression.Lambda<Func<T, T, T>>(addExpr, param1Expr, param2Expr);
_add = expr.Compile(); // <--- error occurs here
}
return _add.Invoke(a, b);
}
}
解决方案
The problem is that your method is generic, introducing a new type parameter T
. So the T
outside the method isn't the same as the T
inside the method.
Just change your method to not be generic:
public static T Add(T a, T b)
... and it should be fine.
To be clearer, your code is currently equivalent to this:
public static class Operators<TC>
{
private static Func<TC, TC, TC> _add = null;
public static TM Add<TM>(TM a, TM b)
{
if (_add == null) {
var param1Expr = Expression.Parameter(typeof(TM));
var param2Expr = Expression.Parameter(typeof(TM));
var addExpr = Expression.Add(param1Expr, param2Expr);
var expr = Expression.Lambda<Func<TM, TM, TM>>
(addExpr, param1Expr, param2Expr);
_add = expr.Compile();
}
return _add.Invoke(a, b);
}
}
Note how I've renamed the T
introduced by the class to TC
, and the T
introduced by the method to TM
. The error message now looks more reasonable:
Test.cs(19,20): error CS0029: Cannot implicitly convert type
'System.Func<TM,TM,TM>' to 'System.Func<TC,TC,TC>'
这篇关于T,T,T>不能从Func键<转换;到Func键< T,T,T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!