gpt4 book ai didi

c# - 不可为 null 的属性为 null

转载 作者:行者123 更新时间:2023-11-30 20:51:15 25 4
gpt4 key购买 nike

我有一个非常简单的类 Address:

public class Address
{
public string Name { get; set; }
public string Country { get; set; }
}

我将 Name 声明为 string 并将 NOT 声明为 string?,因为它永远不应该是

现在我有一个方法,我获取这个类的一个实例作为参数:

public List<Address> SearchAddress(Address search)
{
...
if (!search.Name.Equals(string.Empty))
{
temp = query.Where(a => a.Name.Contains(search.Name));
}
...
}

现在我的同事调用了这个方法,我得到了一个 System.ArgumentNullException 因为 search.Namenull

如果我有一个不可为 null 的 int 属性,如果我不为其分配任何值,我将得到 0 作为值。

如果没有分配值而不仅仅是 string.Empty,为什么不可为 null 的 string 属性为 null

最佳答案

int是一个不可为空的值类型(即 struct )。值类型字段将被初始化为其默认值。例如,int到 0,bool假等。完整列表 here .

当您希望能够分配 null 时对于值类型变量,可以使用Nullable<T> where T : struct或者,如果是 int , Nullable<int>/int? .

string ,另一方面,是一个引用类型。引用类型可以为null,引用类型字段会被初始化为null。因此,拥有 Nullable<string>/string?是不允许的,也没有意义。

在您的情况下,您需要检查 Name 是否字符串为 null 或空

if (! String.IsNullOrEmpty(search.Name)) { ... }

关于c# - 不可为 null 的属性为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21876358/

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