C # CodeGeneration variable as type

In an existing application, code is generated to perform the cast, as shown below: (types are also generated classes, I provide an example with just objectand string)

object o;
string s = (string)o;

When o has a type int, it flings InvalidCastException. So I want to change the code to:

object o;
string s = o as string;

and check back later if there is any string s.

To perform code generation is used System.CodeDom. Listing is generated using the class CodeCastExpression.

I cannot find a way to generate a way variable as type... Can someone help me? Thank!

+3
source share
3 answers

System.ComponentModel.TypeConverter. , , CanConvertFrom(Type) CanConvertTo(Type) ConvertTo, :

public Object ConvertTo(
    Object value,
    Type destinationType
)

: http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx

+1

, :

//For string...
string s = (o == null ? null : o.ToString());
//For int...
int i = (o == null ? 0 : Convert.ToInt32(o));

, if , :

TheType s = null;

if (o is TheType)
    s = (TheType)o

. . , "".

+1

The problem is that the 'as' operator cannot be used with a non-reference type.

For instance:

public class ConverterThingy
{
    public T Convert<T>(object o)
        where T : class
    {
        return o as T;
    }

    public T Convert<T>(object o, T destinationObj)
        where T : class
    {
        return o as T;
    }
}

This should work for most of this. You can convert from any object to another reference type.

SomeClass x = new ConverterThingy().Convert<SomeClass>(new ExpandoObject());
// x is null
SomeClass x = null;
x = new ConverterThingy().Convert(new ExpandoObject(), x);
// x is null, the type of x is inferred from the parameter
0
source

All Articles