简体   繁体   English

如何将A <T>类型的通用对象转换为A <T'>?

[英]How to cast a generic object of type A<T> to A<T'>?

I have a object of type MyClass<object> and I need to convert it to MyClass<int> as I know it is containing ints. 我有一个MyClass<object>类型的MyClass<object> ,我需要将它转换为MyClass<int>因为我知道它包含int。

If I simply try to do the cast is does not compile: 如果我只是尝试做演员是不编译:

MyClass<object> a = new MyClass<object>();
MyClass<int> b = (MyClass<int>) a;

What's wrong and how to do it? 怎么了,怎么办?

You can go with implicit cast operator 您可以使用implicit强制转换运算符

class MyClass<T>
    {
        public static implicit operator MyClass<T>(MyClass<object> input)
        {
            return null;
        }
    }

and then the cast is valid 然后演员表是有效的

MyClass<object> a = new MyClass<object>();
MyClass<int> b = (MyClass<int>) a;

//you don't have to write cast type
MyClass<int> c = a;

though you still need to implement exact details of conversion. 虽然您仍需要实现转换的确切细节。

EDIT : In case you want to call cast explicitely just change implicit keyword to explicit 编辑:如果你想明确地调用强制转换,只需将implicit关键字更改为explicit

class MyClass<T>
    {
        public static explicit operator MyClass<T>(MyClass<object> input)
        {
            return null;
        }
    }

which means that you can still use original cast but this becomes invalid 这意味着你仍然可以使用原始演员,但这变得无效

   //will not compile now !
   MyClass<object> a = new MyClass<object>();
   MyClass<int> b = a;

你不能,因为它们都不是另一个的超类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM