简体   繁体   中英

C# CodeDom Convert between types

I am trying to use CodeDom to produce the following line of code:

object o = (object)bytes

Where "bytes" represents a byte array: byte[] bytes = null;

I could use the VariableDeclaration method or possibly even the CodeAssign method to generate the left side of this line, but how can I create the right side of this line?

I am open to any suggestions - thank you!

Evan

That form of conversion is called casting. Conversion means something along the lines of Convert.ToInt32("123") , or int.Parse("123") .

Cast ( Your exact line object o = (object)bytes; )

var declaration = new CodeVariableDeclarationStatement()
{
    Name = "o",
    Type = new CodeTypeReference(typeof(object)),
    InitExpression = new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("bytes"))
};

Convert ( My conversion sample object o = Convert.ToInt32("123") )

var declaration = new CodeVariableDeclarationStatement()
{
    Name = "o",
    Type = new CodeTypeReference(typeof(object)),
    InitExpression = new CodeMethodInvokeExpression(
        new CodeTypeReferenceExpression(typeof(Convert)),
        "ToInt32",
        new CodePrimitiveExpression("123"))
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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