如何从对象拆箱键入它包含,不知道该类型在编译时? [英] How to unbox from object to type it contains, not knowing that type at compile time?

查看:108
本文介绍了如何从对象拆箱键入它包含,不知道该类型在编译时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行时,我得到了某种类型的包装实例。 ?如何把它拆箱到底层类型

  obj对象; 
字符串变量=一些文本;

OBJ =变量//拳;

//明确拆箱,因为我们知道变量在编译时的类型。

变种X =(字符串)OBJ

//现在让我们假装我们不知道潜在的对象在编译时的类型。

型desiredType = obj.GetType(); //但是我们可以弄清楚。

//现在的问题。
//如何表达这样的事:

变种Y =(desiredType)目标文件; //需要到达这里初始变量的拆箱实例;


解决方案

如果你不知道类型的在编译时间的,那么你就不能拆箱,因为你的无处可把它 - 所有你能做的就是将它存储在对象,这就是:盒装



同样也适用于引用类型,如字符串:您可以' t将其转换为正确的类型,如果你不知道在编译时的类型:你的无处可把它



您<。 EM>可以的特殊情况下的几个类型,例如:

 如果(obj是INT){
INT I =(int)的OBJ;

} ...



另一个技巧是有时的(不经常)有帮助的是切换到的泛型的;然后,而不是在对象方面谈你说的 T 的条款。这...有限的使用虽然。要做到这一点,最简单的方法是通过的动态的,例如:

 动态的obj = ... 
美孚(OBJ);
...
&符LT; T>(T VAL){...与T代码...}

您还可以添加特殊情况下的appreach:

 美孚(字符串VAL){。 ..用绳子...} b美孚(INT VAL){$ b $ ...代码使用int代码...} 

不过,坦白说,我认为它可能是更好的你正在尝试做的,看很难。


At the run-time I get boxed instance of some type. How to unbox it to underlying type?

Object obj;
String variable = "Some text";

obj = variable // boxing;

// explicit unboxing, because we know the type of variable at compile time.

var x = (String)obj     

// Now let's pretend that we don't know the type of underlying object at compile time. 

Type desiredType = obj.GetType(); // But we can figure out.

//And now the question. 
//How to express something like this:

var y = (desiredType)obj; //Need to get unboxed instance of initial variable here; 

解决方案

If you don't know the type at compile time, then you can't unbox because you have nowhere to put it - all you can do is store it in an object, which is: boxed.

The same also applies to reference-types like string: you can't cast it to the right type if you don't know the type at compile time: you have nowhere to put it.

You can special-case a few types, for example:

if(obj is int) {
    int i = (int)obj;
    ...
} ...

Another trick that is sometimes (not often) helpful is to switch into generics; then instead of talking in terms of object you are talking in terms of T. This has... limited use though. The easiest way to do that is via dynamic, for example:

dynamic obj = ...
Foo(obj);
...
Foo<T>(T val) { ... code with T ... }

you can also add special cases to that appreach:

Foo(string val) { ... code with string ...}
Foo(int val) { ... code with int ...}

However, frankly I suggest it may be better to look hard at what you are trying to do.

这篇关于如何从对象拆箱键入它包含,不知道该类型在编译时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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