[英]How use const array with struct C#
我需要在 C# 結構中使用一個數組。 我的部分代碼如下,
這就是我定義 Struct 的方式。
struct customerParameter
{
public const string value1 = "zero";
public const string value2 = "one";
public const string value3 = "theree";
public const string[] multivalues = { "india", "china", "japan" };
}
但是上面的代碼會產生編譯時錯誤,
The expression being assigned to 'customerParameter.multivalues' must be constant.
我在結構中添加了上面的數組,我需要做以下示例代碼的事情。 我需要檢查數組是否包含customerInput
。 處理這個問題的最佳方法是什么? 我如何使用 Struct 和 Array 來做到這一點?
static void Main(string[] args)
{
var customerInput = Console.ReadLine();
if (customerInput == customerParameter.value1)
{
//do something
}
if (customerParameter.multivalues.Contains(customerInput))
{
//my code
}
}
IMO 使用readonly
和constuctor
public readonly string[] multivalues;
public customerParameter()
{
multivalues = new[] { "india", "china", "japan" };
}
編輯
取決於你的最終目標和成就。
如果您的結構用作配置結構,則static readonly IReadOnlyList<string>
是一種方法。
如果您的結構是具有默認值的模型,那么我的答案中的構造方法就是要走的路。 但這需要 C# 10 和更新版本的 C#。 如果您使用的是舊版本的 C#,那么再次堅持static readonly IReadOnlyList<string>
方式。
您不能使用常量。 但是,您可以使用類似的靜態只讀字段:
public static readonly string[] multivalues = new []{ "india", "china", "japan" };
你不能使用常量,在 C# 中Const
意味着它可以在編譯時確定,這就是為什么只有非常原始的類型,如string
、 int
和bool
可以是const
。 因此,您可以使用IReadOnlyList
來表示元素的只讀集合。 閱讀更多:
struct customerParameter
{
public const string value1 = "zero";
public const string value2 = "one";
public const string value3 = "theree";
public static readonly IReadOnlyList<string> MULTIVALUES = new[] { "india", "china", "japan" };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.