C#动态对象初始化不会编译 [英] C# dynamic object initializer won't compile
问题描述
下面的代码似乎是合理的我。它应该创建对象,然后使用动态功能,让我指定我喜欢的任何属性。但是编译器说:ExpandoObject不包含测试的定义。要我说,我知道,那是该死的地步!
动态例如=新ExpandoObject
{
。测试=失败
};
任何想法,为什么CSC是不是不允许这样做。
$ B $ :b
另一种方法是手动展开代码到单独的属性分配
动态例如=新ExpandoObject();
example.Test =不及格;
而烦恼时,我有很多的属性来分配的。
< DIV CLASS =h2_lin>解决方案
在对象初始化,类型是 ExpandoObject
,而不是动态
,这样你就不会得到动态功能。的之后的初始化,您是在类型的变量操作动态
等动态功能的是可用那里。
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.
Within the object initializer, the type is ExpandoObject
, not dynamic
, so you don't get dynamic functionality. After the initializer, you are operating on a variable of type dynamic
and so dynamic functionality is available there.
这篇关于C#动态对象初始化不会编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!