【问题标题】:Why do I need to cast methods to `Action` or `Func` to use it in value tuples?为什么我需要将方法转换为 `Action` 或 `Func` 才能在值元组中使用它?
【发布时间】:2019-02-07 07:00:23
【问题描述】:

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

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

    原因与本案类似:

    Delegate del = x => x * 2; // err
    Delegate del2 = (Func<int,int>)(x => x * 2); // OK
    

    【讨论】:

    • 我现在在 Visual Studio 中看到,当我将鼠标指向这些行中有错误的 GetX 标记时,它会显示“方法组”。我没有意识到我可以有很多具有不同参数的重载,并且它们都用相同的名称标识...
    猜你喜欢
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多