Generic method to type casting

前端 未结 8 1220
不思量自难忘°
不思量自难忘° 2021-02-02 11:55

I\'m trying to write generic method to cast types. I want write something like Cast.To(variable) instead of (Type) variable. My wrong versi

8条回答
  •  耶瑟儿~
    2021-02-02 12:22

    If you can use c# 4.0 this works:

    namespace CastTest
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
    
                A a = new A();
                B b = Cast.To(a);
                b.Test();
    
                Console.Write("Done.");
                Console.ReadKey();
            }
    
            public class Cast
            {
                public static T To(dynamic o)
                {
                    return (T)o;
                }
            }
    
            public class A
            {
                public static explicit operator B(A a)
                {
                    return new B();
                }
            }
    
            public class B
            {
                public void Test()
                {
                    Console.WriteLine("It worked!");
                }
            }
    
        }
    }
    

提交回复
热议问题