Perform implicit display at runtime

So, I have a general class (this is basically a container class) with implicit casting, for example:

public class Container<T> { public T Value { get; set; } public static implicit operator T(Container<T> t) { return t.Value; } public static implicit operator Container<T>(T t) { return new Container<T>() { Value = t }; } } 

So, at runtime, I would like to cast the Container<int> instance to int using reflection, but I canโ€™t find a way, I tried the Cast method mentioned in several places, but I get a Specified cast is not valid. exception Specified cast is not valid. .

Any help would be appreciated.

+6
source share
3 answers

There is almost never a good reason if this type is not internal to an assembly that you cannot change.

But if that were the case, I personally would prefer a clearer dynamic solution (as mentioned by jbtule) to be reflected.

But since you asked for a solution with reflection (maybe you are on .NET 3.5 or earlier?), You can do:

 object obj = new Container<int>(); var type = obj.GetType(); var conversionMethod = type.GetMethod("op_Implicit", new[] { type }); int value = (int)conversionMethod.Invoke(null, new[] { obj }); 
+4
source

Using dlr, the open source ImpromptuInterface in nuget, you can dynamically invoke implicit or explicit casting .

 int intInstance =Impromptu.InvokeConvert(containerInstance, typeof(int)); 

although this example is quite complex and can be done with

 int intInstance = (dynamic) containerInstnace; 

. but if you do not know int at compile time, then Impromptu is the way to go.

+1
source

Entering implicit statements allows you to do translations implicitly. In other words, this is completely legal:

 int i = new Container<int>() { Value = 2 }; if (i == 2) { // This will be executed } 

If you only have a Container<object> then this will not work, but in any case, your code should probably be refactored anyway, since you are essentially ignoring the general parameter that you have.

0
source

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


All Articles