繁体   English   中英

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

[英]How to construct object using C# - CodeDOM

我有将值分配给属性并使用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;
}

对于原始值,它可以正确生成语句。 但是,对于其余时间(例如DateTime),它会生成类似testObj.PurchasedOn = "17-09-2016 18:50:00";语句testObj.PurchasedOn = "17-09-2016 18:50:00"; 一种使用目标数据类型“解析”方法的方法。 但是它可能不适用于其他数据类型。 如何构造对象? 框架中是否有可用的方法?

您面临的问题是您试图将值分配给变量,而该变量是对象数据类型。

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,它将被正确存储。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM