进行隐式转换时,c#委托类型推断不能按预期工作

时间:2017-12-20 14:16:48

标签: c# delegates implicit-conversion

我和代表们一起玩,我遇到了以下问题:

  • c#推断出委托的错误类型
  • c#从方法组转换为委托但不是所有时间

转到代码:

public delegate void Act(int i);
public delegate Task ActAsync(int i);

public class Actor
{
    public Act Act { get; private set; }
    public ActAsync ActAsync { get; private set; }

    public static implicit operator Actor(Act act)
    {
        return new Actor { Act = act };
    }

    public static implicit operator Actor(ActAsync actAsync)
    {
        return new Actor { ActAsync = actAsync };
    }
}

public class Class1
{
    public void ActMethodGroup(int i) { }

    public async Task ActAsyncMethodGroup(int i){}

    public void Test()
    {
        Act act = (i) => { };
        ActAsync actAsync = async (i) => { };
        List<Actor> actors = new List<Actor> {
            (i) => { },         //compiler error: Not all code paths return a value in lambda expression of type 'ActAsync'
            async (i) => { },   //compiler error: Cannot convert lambda expression to type 'Actor' because it is not a delegate type
            act,                //works fine because act is of type 'Act'
            actAsync,           //works fine because actAsync is of type 'ActAsync'
            ActMethodGroup,     //compiler error: Cannot convert from 'method group' to Actor
            ActAsyncMethodGroup //compiler error: Cannot convert from 'method group' to Actor
        };

        List<Act> actList = new List<Act>
        {
            act,                //works fine because act is of type 'Act'
            ActMethodGroup      //works fine, but why?
        };

        List<ActAsync> actAsyncList = new List<ActAsync>
        {
            actAsync,           //works fine because actAsync is of type 'ActAsync'
            ActAsyncMethodGroup //works fine, but why?
        };
    }
}

问题:

  • 为什么(i) => { } lambda在new List<Actor>列表初始化程序
  • 中传递时与ActAsync匹配而不是Act
  • 为什么在async (i) => { }列表初始化程序中传递new List<Actor>时类型推断失败
  • 为什么ActMethodGroup会在new List<Act>初始值设定项中转换为正确的类型,但不会转换为new List<Actor>初始值设定项

0 个答案:

没有答案
相关问题