给字符串一个空值

Giving a string a null value

我需要一些关于如何将下面代码片段中的字符串设置为 null 值的信息。

[Index(IsUnique = true)]
[StringLength(450)]
public string StockCode
{
    get { return _stockCode; }
    set { _stockCode = value.ToUpper(); } //(ToUpper)<<-- Error
}

当我尝试以正常方式进行操作时 public string? StockCode 我在 .ToUpper 收到错误,它说:

'System.Nullable' does not contain a definition for 'ToUpper' and no extension method 'ToUpper' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)

我不是专家或专业的 C# 编码员,所以我不知道如何将我的字符串设置为空值并仍然按照我尝试的方式使用 .ToUpper。 :( 如有任何建议,我们将不胜感激!

您不能在字符串上使用可空类型。默认情况下,字符串接受空值,可以通过 string.IsNullOrEmpty(StockCode);

检查

不确定当您尝试获取这个时是否要面对所有复杂情况属性,但只需在应用 ToUpper() 之前添加对空值的检查

set { _stockCode = (value == null ? null : value.ToUpper()); }