2026-05-15 C# public string Brand { get; set; } 二行出現警告, 不可為 Null

‘2026-05-15 C# public string Brand { get; set; } 二行出現警告, 不可為 Null ‘

我:
public string Brand { get; set; }

public string Color { get; set; } 

這二行出現警告, 不可為 Null , 那麼要怎麼改比較好?

GPT:
如果屬性 BrandColor 不應為 null,有幾種方式可以解決這個警告,讓代碼更加安全並遵循最佳實踐。以下是一些常見的解決方案:

方法 1:使用空字串作為預設值

你可以將屬性的初始值設為空字串,這樣可以保證它們不會是 null

1
2
public string Brand { get; set; } = string.Empty;
public string Color { get; set; } = string.Empty;

這樣做的好處是,屬性在初始化時會自動設置為空字串 "",因此不會是 null,避免可能的空值問題。

方法 2:使用建構函數進行初始化

另一種方法是強制要求通過建構函數來初始化這些屬性,以確保它們不會被設為 null

1
2
3
4
5
6
7
8
9
10
11
12
public class Car
{
public string Brand { get; set; }
public string Color { get; set; }

// 建構函數,強制要求設置 Brand 和 Color
public Car(string brand, string color)
{
Brand = brand ?? throw new ArgumentNullException(nameof(brand));
Color = color ?? throw new ArgumentNullException(nameof(color));
}
}

使用這樣的建構函數,你可以確保創建 Car 物件時,必須提供 BrandColor,因此它們不能為 null

使用範例:

1
2
Car myCar = new Car("Toyota", "Red");
// 創建物件時必須提供 Brand 和 Color

方法 3:使用 required 屬性(C# 11 及以上)

如果你使用的是 C# 11 或更新的版本,可以使用 required 關鍵字來強制要求在初始化物件時設置屬性。這樣可以確保屬性被正確地初始化。

1
2
3
4
5
public class Car
{
public required string Brand { get; set; }
public required string Color { get; set; }
}

使用範例:

1
2
Car myCar = new Car { Brand = "Toyota", Color = "Red" };
// 創建物件時,必須設置 Brand 和 Color 屬性

這樣做可以避免未初始化的屬性為 null,提高代碼的安全性。

總結

  • 方法 1:使用空字串作為預設值,簡單且避免 null 的問題。
  • 方法 2:使用建構函數強制初始化屬性,確保在物件創建時提供必要的值。
  • 方法 3:使用 C# 11 的 required 屬性強制在物件初始化時設置屬性。

以上三種方法都可以解決屬性可能為 null 的警告,你可以根據需要選擇合適的方案。如果你希望屬性必須被設置,且你的 C# 版本支持 required,那麼方法 3 是最直接的選擇;如果你希望使用舊版本或更靈活的初始化控制,建議使用方法 2。