c# - Generic method to type casting -


i'm trying write generic method cast types. want write cast.to<type>(variable) instead of (type) variable. wrong version of method:

public class cast {     public static t to<t>(object o)     {         return (t) o;     } } 

and simple test:

public class {     public static explicit operator b(a a)     {         return new b();     } }  public class b { }  a = new a(); b b = cast.to<b>(a); 

as guessed, code fail invalidcastexception.

is code fail because virtual machine doesn't know how cast variable of type object type b @ run-time? exception message says: "unable cast object of type type b". clr knows real type of variable o, why cannot perform casting?

and here main question: how should rewrite method t to<t>(object o) fix problem?

if can use c# 4.0 works:

namespace casttest {     internal class program     {         private static void main(string[] args)         {              a = new a();             b b = cast.to<b>(a);             b.test();              console.write("done.");             console.readkey();         }          public class cast         {             public static t to<t>(dynamic o)             {                 return (t)o;             }         }          public class         {             public static explicit operator b(a a)             {                 return new b();             }         }          public class b         {             public void test()             {                 console.writeline("it worked!");             }         }      } } 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -