gpt4 book ai didi

c# - 使用 as 运算符来构造对象

转载 作者:行者123 更新时间:2023-12-02 01:47:36 25 4
gpt4 key购买 nike

为什么第一个有效但第二个无效?将对象转换为结构时有什么需要担心的吗?

struct Hex { /* ... */ }
object actionData = GetData();

1:

bool isHex = actionData is Hex;
Hex hexx = (Hex)actionData;

2:

Hex hex = actionData as Hex;

最佳答案

因为as operator如果类型检查失败,则返回 null:

The expression of the form E as Twhere E is an expression that returns a value and T is the name of a type or a type parameter, produces the same result as: E is T ? (T)(E) : (T)null except that E is only evaluated once.

如果 T 是不可空值类型,则无法完成此操作(因此编译器会发出错误)。使用可空值类型作为 T 可以工作:

object actionData = new Hex(); // your code returning boxed Hex
Hex? hex = actionData as Hex?;
if(hex.HasValue)
{
...
}

关于c# - 使用 as 运算符来构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70729861/

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