为什么我需要将方法强制转换为`Action`或`Func`以在值元组中使用它?

问题描述 投票:0回答:1

为什么编译器无法处理这些x3x4赋值?

    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;
    }
c# .net tuples c#-7.0 valuetuple
1个回答
2
投票

因为元组没有具体类型,除非您将其转换为更具体的类型。您的GetX方法可以转换为各种委托类型。所以你需要将它转换为特定的一个,编译器不能为你选择它。

原因与此案相似:

Delegate del = x => x * 2; // err
Delegate del2 = (Func<int,int>)(x => x * 2); // OK
© www.soinside.com 2019 - 2024. All rights reserved.