Since this is generic type without a constraint compiler has no knowledge if the types involved will have '+' overloaded hence the compiler error
These are some workarounds
public static TResult Add<T1, T2, TResult>(T1 left, T2 right, Func<T1, T2, TResult> AddMethod)
{
return AddMethod(left, right);
}
var finalLabel = Add("something", 3,(a,b) => a + b.ToString());
Below code could let you build same but evaluated at run time so not run time safe
public static T AddExpression<T>(T left, T right)
{
ParameterExpression leftOperand = Expression.Parameter(typeof(T), "left");
ParameterExpression rightOperand = Expression.Parameter(typeof(T), "right");
BinaryExpression body = Expression.Add(leftOperand, rightOperand);
Expression<Func<T, T, T>> adder = Expression.Lambda<Func<T, T, T>>(
body, leftOperand, rightOperand);
Func<T, T, T> theDelegate = adder.Compile();
return theDelegate(left, right);
}
Il compilatore C# esegue questa operazione in modo da non scrivere codice buggato. Se T è sconosciuto al compilatore non sa come aggiungere i valori di T. Inoltre non conosce il tipo di risultato di T, in questo caso l'aggiunta. – JonH
Gli argomenti sono forzati ad essere "di tipo numerico" ?? –