c# - 如何从对象拆箱到它包含的类型,在编译时不知道该类型?

标签 c# unboxing

在运行时,我得到某种类型的盒装实例。如何将其拆箱为基础类型?

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; 

最佳答案

如果您在编译时不知道类型,那么您就无法拆箱,因为您无处可放 - 您所能做的就是存储它在 object 中,它是:boxed.

这同样适用于像 string 这样的引用类型:如果您在编译时不知道类型,则无法将其转换为正确的类型:您无处可去把它

可以对一些类型进行特殊处理,例如:

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

另一个有时(不经常)有用的技巧是切换到泛型;那么不是用 object 来说话,而是用 T 来说话。这……虽然用途有限。最简单的方法是通过动态,例如:

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

您还可以为该应用程序添加特殊情况:

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

但是,坦率地说,我建议仔细看看您正在尝试做什么可能会更好。

关于c# - 如何从对象拆箱到它包含的类型,在编译时不知道该类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15565196/

相关文章:

c# - 在时间轴恒定的位置和速度给定点的情况下构造曲线桥图的算法

C# 类型推断获取错误的类型

c# - 从对象中拆箱值类型

Java对方法返回值的拆箱

c# - 是否可以使一段代码原子化 (C#)?

c# - Assert.AreEqual() 与 System.Double 变得非常困惑

c# - 无法转换类型为 '<>f__AnonymousType5` 6 的对象

java - 如果包装器使用拆箱,需要什么 intValue() 方法?

c# - C# 中动态数据类型的装箱和拆箱工作原理

c# - Microsoft Message Queue - 优先级标志或单独的队列?