0

为什么编译器不能处理这些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;
    }
4

1 回答 1

2

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

原因与本案类似:

Delegate del = x => x * 2; // err
Delegate del2 = (Func<int,int>)(x => x * 2); // OK
于 2018-09-01T14:38:33.537 回答