Cannot convert lambda expression to type #39;object#39; because it is not a delegate type(无法将 lambda 表达式转换为类型“对象,因为它不是委托类型)
问题描述
我有一个基类,它的 bool 属性如下所示:
I have a base class that has a bool property which looks like this:
public abstract class MyBaseClass
{
public bool InProgress { get; protected set; }
}
我正在从它继承另一个类并尝试将 InProgress 作为代表添加到字典中.但它给我一个错误.这就是我的派生类的样子:
I am inheriting it another class from it and trying to add InProgress as a delegate to the dictionary. But it throws me an error. This is how my Derived class looks like:
public abstract class MyClass
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("InProgress", InProgress => base.InProgress = InProgress);
}
这是我得到的错误:
无法将 lambda 表达式转换为类型对象",因为它不是委托类型
Cannot convert lambda expression to type 'object' because it is not a delegate type
我在这里做错了什么?
推荐答案
最好是强类型的字典,但是如果你先将 lambda 分配给特定的 lambda(委托),它应该可以工作(因为编译器然后知道委托格式):
Best would be to have the dictionary strongly typed, but if you assign the lambda to a specific lambda (delegate) first, it should work (because the compiler then knows the delegate format):
Action<bool> inp = InProgress => base.InProgress = InProgress;
dict.Add("InProgress", inp);
或者直接施法,效果一样
dict.Add("InProgress", (Action<bool>)(InProgress => base.InProgress = InProgress));
当然,拥有像对象这样的字典格式是可以讨论的,因为您必须知道委托格式才能使用它.
Of course having such a dictionary format as object is discussable, since you'll have to know the delegate format to be able to use it.
这篇关于无法将 lambda 表达式转换为类型“对象",因为它不是委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法将 lambda 表达式转换为类型“对象",因为它不是委托类型


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01