为什么我需要将方法转换为“Action”或“Func”才能在值元组中使用它?
Why do I need to cast methods to `Action` or `Func` to use it in value tuples?
为什么编译器无法处理这些 x3
和 x4
赋值?
void X()
{
(Func<int, int>, int) x1 = (GetX, 1); // OK
object x2 = x1; // OK
object x3 = (GetX, 1); // Error CS8135 Tuple with 2 elements cannot be converted to type 'object'.
object x4 = (GetX, 1) as (Func<int, int>, int); // Error CS8307 The first operand of an 'as' operator may not be a tuple literal without a natural type.
object x5 = ((Func<int, int>, int))(GetX, 1); // OK
object x6 = ((Func<int, int>)GetX, 1); // OK
}
int GetX(int x)
{
return x;
}
因为元组没有具体类型,除非您将其转换为更具体的类型。您的 GetX
方法可以转换为各种委托类型。所以你需要把它转换成一个特定的,编译器不能为你选择它。
原因与本例类似:
Delegate del = x => x * 2; // err
Delegate del2 = (Func<int,int>)(x => x * 2); // OK
为什么编译器无法处理这些 x3
和 x4
赋值?
void X()
{
(Func<int, int>, int) x1 = (GetX, 1); // OK
object x2 = x1; // OK
object x3 = (GetX, 1); // Error CS8135 Tuple with 2 elements cannot be converted to type 'object'.
object x4 = (GetX, 1) as (Func<int, int>, int); // Error CS8307 The first operand of an 'as' operator may not be a tuple literal without a natural type.
object x5 = ((Func<int, int>, int))(GetX, 1); // OK
object x6 = ((Func<int, int>)GetX, 1); // OK
}
int GetX(int x)
{
return x;
}
因为元组没有具体类型,除非您将其转换为更具体的类型。您的 GetX
方法可以转换为各种委托类型。所以你需要把它转换成一个特定的,编译器不能为你选择它。
原因与本例类似:
Delegate del = x => x * 2; // err
Delegate del2 = (Func<int,int>)(x => x * 2); // OK