C# 动态对象初始值设定项无法编译
下面的代码对我来说似乎是合理的。它应该创建对象,然后使用动态功能让我分配我喜欢的任何属性。然而编译器说“ExpandoObject 不包含 Test 的定义”。对此我说:“我知道,这就是问题所在!”
dynamic example = new ExpandoObject
{
Test = "fail"
};
任何想法为什么 csc 不允许这样做。
另一种方法是手动将代码扩展为单独的属性分配。
dynamic example = new ExpandoObject();
example.Test = "fail";
当我有很多属性要分配时,这很烦人。
The following code seems reasonable to me. It should create the object and then use the dynamic features to let me assign any properties I like. However the compiler says that "ExpandoObject does not contain a definition for Test". To which I say, "I know, that's the freaking point!"
dynamic example = new ExpandoObject
{
Test = "fail"
};
Any ideas why csc isn't allowing this.
The alternative is to manually expand the code into individual property assignments.
dynamic example = new ExpandoObject();
example.Test = "fail";
Which is annoying when I have lots of properties to assign.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在对象初始值设定项中,类型为
ExpandoObject
,而不是dynamic
,因此您无法获得动态功能。 初始化程序之后,您正在操作动态
类型的变量,因此动态功能在这里可用。Within the object initializer, the type is
ExpandoObject
, notdynamic
, so you don't get dynamic functionality. After the initializer, you are operating on a variable of typedynamic
and so dynamic functionality is available there.在第一个示例中,C# 编译器将在 ExpandoObject 上查找名为 Test 的属性。它不存在。
在第二个示例中,编译器将在动态对象上查找 Test 属性。这是允许的,因此可以编译。
In your first example, the C# compiler will look for a property named Test on the ExpandoObject. It doesn't exist.
In your second example, the compiler will look for a Test property on a dynamic object. This is allowed, so it compiles.