reflection - Is it possible to use implicit casts with types created at run-time in c#? -
i'm creating type @ runtime using reflection.emit
. problem whenever instantiate instance of new type have use object
or dynamic
because type isn't known @ compile time. works fine except when want type implicitly cast new type during assignment. variable happily takes on new value , it's corresponding type without attempting cast current type.
is there way create variable of newly created type allow implicit casting? i'm happy give compile-time checking these casts @ least attempted @ run-time.
edit:
here example make more clear. happens when know type @ compile-time:
myclass a; //this calls implicit cast operator , 'a' stays of same type = 5;
and happens if don't:
type t = createtypeusingtypebuilder(); object = activator.createinstance(t); //this not call implicit cast operator , 'a' becomes in integer = 5;
also, i'm not surprised @ behavior or asking why happens. i'm asking if there sort of workaround achieve desired behavior of having check implicit operator @ run-time.
in order understand why not possible, @ least not directly, 1 needs understand how implicit conversion operators work in first place.
when write this
mynumerictype x = new mynumerictype(123); double y = x;
the compiler realizes x
, y
of different types, , searches mynumerictype
see if there implicit conversion operator defined:
public static implicit operator double(mynumerictype n) { return n.doublevalue; }
once operator found, compiler invokes if regular static
method (which is).
when work types generated @ runtime, should generate conversion @ runtime well. example, if this
private static func<object,object> makeconverter(type t1, type t2) { var p = expression.parameter*(typeof(object)); var efrom = expression.convert(p, t1); var eto = expression.convert(efrom, t2); var res = expression.convert(eto, typeof(object)); var lambda = expression.lambda<func<object,object>>(res, new[] { p }); return (func<object,object>)lambda.compile(); }
with method in place can this:
type runtimetype1 = ... type runtimetype2 = ... var converter = makeconverter(runtimetype1, runtimetype2); object objruntimetype1 = ... object objruntimetype2 = converter(objruntimetype1);
Comments
Post a Comment