Domanda

I'm dynamically creating an expression tree using values provided in an XML file (i.e. I read strings). The value and the type of the member are read from this file. I'm trying to create a ConstantExpression of an integer:

XElement expression = GetMyCurrentMember();
//<member type="System.Int32">5</member>

return Expression.Constant(expression.Value, Type.GetType(expression.Attribute("type").Value, false, true));

In the return statement I'm getting the error Argument types do not match which, upon inspection, seams about right since I'm passing a string and saying it's an int. A simple cast would (probably) solve the problem but that means that I'm loosing the dynamic of the whole system. Instead of int I could have double or char or even a custom type and I don't really want to create a different call or method for every type. Is there a method to "force" the automatic conversion of the input value to the requested type?

È stato utile?

Soluzione 2

I think for a wide variety of types, a simple Convert.ChangeType will do the trick:

XElement expression = GetMyCurrentMember();
//<member type="System.Int32">5</member>
var formatProv = CultureInfo.InvariantCulture;
var type = Type.GetType(expression.Attribute("type").Value, false, true);
var value = Convert.ChangeType(expression.Value, type, formatProv);
return Expression.Constant(value, type);

Please note that by providing a format provider you can explicitly specify the culture you want to use in the conversion.

Altri suggerimenti

You could "convert" the value, but you need to decide what to do if the conversion fails:

string value = expression.Value;
Type type = Type.GetType(expression.Attribute("type").Value, false, true);

return Expression.Constant(Convert.ChangeType(value, type), type);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top