CS0828错误:无法将方法组分配给匿名类型属性求助
问题原因与解决方法
错误根源
你以为自己在实例化XX类,但实际上new { ... }是C#里匿名类型的初始化语法,不是你定义的XX类的实例化写法。编译器把这段代码识别成创建匿名类型,而匿名类型的属性无法直接接收方法组(DoSomething就是方法组),所以报了CS0828错误。
修复代码
把实例化的代码改成明确指定XX类:
// A basic function that takes an int and has void return private static void DoSomething(int d) { // .... do stuff }; // A class is defined with an Action<int> delegate private class XX { public Action<int> YY { get; set; } } // 明确实例化XX类,而非匿名类型 private static readonly XX xx = new XX { YY = DoSomething };
为什么这样能解决?
当你写new XX { ... }时,编译器知道你要创建XX类的实例,YY的类型是明确的Action<int>,DoSomething方法的签名和Action<int>匹配,能隐式转换为该委托类型,自然就不会报错了。
内容的提问来源于stack exchange,提问作者Chris Walsh
相关产品推荐
相关产品推荐

