Is it possible to use implicit casts created at runtime in C #?

I am creating a type at runtime using Reflection.Emit. The problem is that whenever I create an instance of a new type, I have to use objector dynamic, because this type is unknown at compile time. This works fine unless I would like a different type to implicitly cast to a new type at the time of assignment. The variable happily accepts the new value and the corresponding type, without trying to apply it to the current type.

Is there a way to create a variable of the type just created that allows the use of implicit casting? I would gladly refuse to check the compilation time, but I would like these casts to be taken at least at runtime.

Edit:

Here is an example to make it more understandable. This is what happens when you know the type at compile time:

MyClass a;
//this calls the implicit cast operator and 'a' stays of the same type
a = 5;

and this will happen if you do not:

Type t = CreateTypeUsingTypeBuilder();
object a = Activator.CreateInstance(t);
//this does not call the implicit cast operator and 'a' just becomes in integer
a = 5;

In addition, I am not surprised at this behavior or ask why this is happening. I ask if there is any solution to achieve the desired behavior when it checks for an implicit statement at runtime.

+4
source share
2 answers

, , , , , .

-

MyNumericType x = new MyNumericType(123);
double y = x;

, x y MyNumericType, , :

public static implicit operator double(MyNumericType n) {
    return n.doubleValue;
}

, , static ( ).

, , . ,

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();
}

:

Type runtimeType1 = ...
Type runtimeType2 = ...
var converter = MakeConverter(runtimeType1, runtimeType2);
object objRuntimeType1 = ...
object objRuntimeType2 = converter(objRuntimeType1);
+2

, , , - , , .

, , - ( ). , , , , , :

Type t = CreateTypeUsingTypeBuilder();
object a = Activator.CreateInstance(t, 5);

, . MissingMethodException, .

- , , , , - . , , Activator, , . , .

public interface IMyWrapper<T>
{
    IMyWrapper<T> Convert(T value);
}

, , - , , .

0

Source: https://habr.com/ru/post/1627791/


All Articles