如何使用c# - CodeDOM构造对象

本文关键字:对象 CodeDOM 何使用 | 更新日期: 2023-09-27 18:07:16

我有一个方法,可以给属性赋值,并使用c# CodeDOM生成代码语句。

private static CodeAssignStatement setProp(string propName, object propValue, Type propType, Type objType)
{
                CodeAssignStatement declareVariableName = null;
                if (propType.IsPrimitive)
                {
                    declareVariableName = new CodeAssignStatement(
                   new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("testObj"), propName), new CodePrimitiveExpression(propValue)
                   );
                }
                else
                {
                    declareVariableName = new CodeAssignStatement(
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("testObj"), propName),
                     new CodeVariableReferenceExpression("'"" + propValue?.ToString() + "'"")
                    );
                }
                return declareVariableName;
}

对于原始值,它正在正确生成语句。然而,对于rest,例如DateTime,它会生成testObj.PurchasedOn = "17-09-2016 18:50:00";这样的语句。使用目标数据类型"Parse"方法的一种方法。但它可能不适用于其他数据类型。我如何构造对象?框架中是否有可用的方法?

如何使用c# - CodeDOM构造对象

您面临的问题是,您正在尝试将值赋给变量,该变量是对象数据类型。

int i = 123; // This is fine as it assigns the primitive value 123 to the integer variable i.
string s = "123"; // This is also fine as you're assigning the string value "123" to the string variable s.
string t = s; // This is fine as long as variable s is a string datatype.

你的代码正在尝试给一个对象数据类型赋值。

testObj.PurchasedOn = "17-09-2016 18:50:00"; // This won't work as you cannot assign a string constant to a DateTime variable.

正如您所提到的,如果可用,您可以使用Parse方法。

如果我们看一下你期望生成的代码,它很可能是这样的:

testObj.PurchasedOn = new DateTime(2016, 09, 17, 18, 50, 0);

可以看到,对于DateTime对象构造函数,您需要指定6个参数。对于您希望创建的每个对象类型,这显然会有所不同。

解决方案在于CodeObjectCreateExpression类,它可以代替CodePrimitiveExpression类。

我建议改变你的方法,接受CodeExpression而不是object propValue。这样你就可以提供一个原语或对象实例化器。

在这种情况下,你可以传递给你的方法:

new CodeObjectCreateExpression(typeof(DateTime), 2016, 09, 17, 18, 50, 0);

您可以在这里找到更多关于CodeObjectCreateExpression的详细信息。

如果你只是摆脱条件,并做:

private static CodeAssignStatement setProp(string propName, object propValue, Type propType, Type objType)
{
    CodeAssignStatement declareVariableName = null;
    declareVariableName = new CodeAssignStatement(
        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("testObj"), propName),
        new CodePrimitiveExpression(propValue)
    );
    return declareVariableName;
}

CodePrimitiveExpression似乎接受一个对象,这意味着你可以给它分配几乎任何东西。因此,如果传入一个DateTime,它将被正确地存储。