在 C# 运行时创建自定义对象

发布于 2024-09-28 05:58:34 字数 332 浏览 2 评论 0原文

我想在运行时用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

讽刺将军 2024-10-05 05:58:34

您可以通过 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.

柠檬色的秋千 2024-10-05 05:58:34

抱歉,我的 C# 很生疏,所以我会用 VB 来解决这个问题。我能想到的唯一方法是使用对象类型。查看下面的属性类型定义和实例化方法:

Private m_myVal As Object
Public Property myVal() As Object
    Get
        Return m_myVal
    End Get
    Set(ByVal value As Object)
        m_myVal = value
    End Set
End Property

Public Sub New(ByVal valType As String, ByVal val As Object)
    If valType = "string" Then
        myVal = CType(val, String)
    ElseIf valType = "date" Then
        myVal = CType(val, Date)
    End If
End Sub

然后,例如,创建该类的新实例,如下所示:

Dim myDynamicClass as New Class1("date","10/21/2010")

您的 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:

Private m_myVal As Object
Public Property myVal() As Object
    Get
        Return m_myVal
    End Get
    Set(ByVal value As Object)
        m_myVal = value
    End Set
End Property

Public Sub New(ByVal valType As String, ByVal val As Object)
    If valType = "string" Then
        myVal = CType(val, String)
    ElseIf valType = "date" Then
        myVal = CType(val, Date)
    End If
End Sub

Then, for example, create a new instance of the class as:

Dim myDynamicClass as New Class1("date","10/21/2010")

Your myval property will have a date typed value stored.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文