通用方法的类型转换 [英] Generic method to type casting

查看:119
本文介绍了通用方法的类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写通用的方法来流延类型。我想写点东西像 Cast.To<类型>(可变),而不是的(类型)变量。 我错了版本的方法:

I'm trying to write generic method to cast types. I want write something like Cast.To<Type>(variable) instead of (Type) variable. My wrong version of this method:

public class Cast
{
    public static T To<T>(object o)
    {
        return (T) o;
    }
}

这是简单的测试:

And this is simple test:

public class A
{
    public static explicit operator B(A a)
    {
        return new B();
    }
}

public class B
{
}

A a = new A();
B b = Cast.To<B>(a);

正如你猜到了,code将无法与 InvalidCastException的

这是code失败,因为虚拟机不知道怎么投类型的变量对象键入 B 在运行时?但是,异常消息说:无法投类型A的对象,B型。因此,CLR知道变量的实际类型 0 ,为什么它不能执行铸造?

Is this code fail because virtual machine doesn't know how to cast variable of type object to type B at run-time? But exception message says: "unable to cast object of type A to type B". So CLR knows about real type of variable o, why it cannot perform casting?

这里是主要的问题:我应该怎么改写方法 T到&lt; T&GT;(对象o)来解决这个问题。

And here is main question: how should I rewrite method T To<T>(object o) to fix this problem?

推荐答案

如果您可以使用C#4.0本作品:

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<B>(a);
            b.Test();

            Console.Write("Done.");
            Console.ReadKey();
        }

        public class Cast
        {
            public static T To<T>(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!");
            }
        }

    }
}

这篇关于通用方法的类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆