在 C# 运行时创建自定义对象
我想在运行时用 C# 创建自定义对象,这些对象将具有从 xml 文件导入的属性。 xml 文件看起来像这样:
<field name="FirstName" value="Joe" type="string" />
<field name="DateAdded" value="20090101" type="date" />
我想在 c# 中创建具有 FirstName 和 DateAdded 等属性的对象,并且具有正确的属性类型。我该怎么做?我尝试使用带有 if 语句的函数来根据“type”属性确定类型,但我也想动态评估类型。
谢谢。
I want to create custom objects in C# at runtime, the objects will have properties imported from an xml file. The xml file looks something like this:
<field name="FirstName" value="Joe" type="string" />
<field name="DateAdded" value="20090101" type="date" />
I would like to create objects in c# that have properties such as FirstName and DateAdded and that have the correct type for the properties. How can I do this? I have tried using a function with if statements to determine the type based on the "type" attribute but I would like to evaluate the types on the fly as well.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过 CodeDOM 执行此操作,或者使用
dynamic 更轻松地执行此操作
和 ExpandoObject。但是,请意识到,如果不提前了解类型,就很难有效地使用它们。通常,创建
Dictionary
或类似选项是更简单的选择。You can do this via CodeDOM, or more easily using
dynamic
and ExpandoObject.However, realize that, without knowing the types in advance, it's difficult to use them effectively. Often, making a
Dictionary<TKey, TValue>
or similar option is an easier choice.抱歉,我的 C# 很生疏,所以我会用 VB 来解决这个问题。我能想到的唯一方法是使用对象类型。查看下面的属性类型定义和实例化方法:
然后,例如,创建该类的新实例,如下所示:
您的 myval 属性将存储一个日期类型的值。
Sorry, my C#'s rusty, so Ill tackle this in VB. Only way I can figure to do it is to use an Object type. Check out the property type definition and instantiation method below:
Then, for example, create a new instance of the class as:
Your myval property will have a date typed value stored.