Problem using C # generators with method overload

I am trying to call an overloaded method based on a generic type. I did this in C ++ without pain. But I really don't understand why I cannot do this in C # with generics. Can someone help me how can I achieve this in C # using generics?

class Test<T> { public T Val; public void Do(T val) { Val = val; MainClass.Print(Val); } } class MainClass { public static void Print(UInt16 val) { Console.WriteLine("UInt16: " + val.ToString()); } public static void Print(UInt32 val) { Console.WriteLine("UInt32: " + val.ToString()); } public static void Print(UInt64 val) { Console.WriteLine("UInt64: " + val.ToString()); } public static void Main (string[] args) { Test<UInt16> test = new Test<UInt16>(); test.Do(0); } } 
+4
source share
3 answers

This will not work, because C # generators are fundamentally different from C ++ templates. Created instances of the universal class are created at runtime, while instances of C ++ templates are created at compile time (as far as I know, my C ++ is very rusty). The general Do<T> method must know at compile time one invocation method that can be baked as a result of IL.

A way to achieve this is to use reflection or dynamic (new in C # 4):

 class Test<T> { public T Val; public void Do(T val) { Val = val; dynamic dynVal = Val; MainClass.Print(dynVal); } } 

With dynamic method search will be performed at runtime. Please note that this is completely dependent on generics and will work equally well in non-standard code.

+4
source

Something may be missing for me, but in your code you have:

 public void Do(T val) { Val = val; MainClass.Print(Val); } and in you main method you have: test.Do(); //no parameter provided. 
+1
source

The problem you are facing is that C # does not select the appropriate method based on your type T. You will need to do the following:

 void Print<T>(T val) { switch(val.GetType()) { case typeof(UInt64): Console.WriteLine(...); break; } } 
+1
source

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


All Articles