gpt4 book ai didi

c# - 如何根据定义使 'struct' 可空?

转载 作者:IT王子 更新时间:2023-10-29 03:51:34 26 4
gpt4 key购买 nike

struct AccountInfo
{
String Username;
String Password;
}

现在如果我想要一个 Nullable例如我应该写:

Nullable<AccountInfo> myAccount = null;

但我想制作 struct Nullable从本质上讲,它可以像这样使用(不使用 Nullable<T> ):

AccountInfo myAccount = null;

最佳答案

你不能。结构被视为值类型,根据定义不能为空。使其成为nullable 的最简单方法是使其成为引用类型。

您需要问自己的答案是“为什么这是一个结构?”除非你能想到一个真正可靠的理由,否则不要,并把它作为一个类。关于结构“更快”的论点确实被夸大了,因为结构不一定是在堆栈上创建的(您不应该依赖于此),并且“获得”的速度因具体情况而异。

参见 post埃里克·利珀特 (Eric Lippert) 关于类与结构的辩论和速度。

关于c# - 如何根据定义使 'struct' 可空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4491869/

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