我和代表们一起玩,我遇到了以下问题:
转到代码:
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>
列表初始化程序async (i) => { }
列表初始化程序中传递new List<Actor>
时类型推断失败ActMethodGroup
会在new List<Act>
初始值设定项中转换为正确的类型,但不会转换为new List<Actor>
初始值设定项