gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:19:02 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com