我有一個固定的字串串列,我把它放在一個陣列中。我正在使用IndexOf()以便從這樣的陣列中獲取一個元素,但這似乎不起作用:
using System.Runtime;
...
static string[] Alarm_Names = new string[3] {"A1", "A2", "A3"}
static bool[] arr_Alarms = new bool[3] {false, false, false};
internal static void HandleAlarm(..., string code, ...)
{
if (arr_Alarms[IndexOf(Alarm_Names, code)]) return; // does not compile
if (arr_Alarms[Array.IndexOf(Alarm_Names, code)]) return; // does not compile
函式/靜態方法IndexOf()似乎不存在,盡管本頁另有提及。
這很可能是因為我使用 C# 編程,.Net Framework 4.6.1,對于提到的頁面的 .Net 6 版本來說還不夠新。
如您所見,我有一個常量字串串列,我想為每個字串創建一個布爾串列,如果將字串作為函式引數輸入,我想檢查布爾串列以檢查價值,而該功能IndexOf()是實作這一目標的完美工具。
還有其他簡單的方法嗎? (或者我的分析是錯誤的,我可以做一些非常簡單的事情來完成這項作業,而不修改我的目標 .Net 框架的版本嗎?)
uj5u.com熱心網友回復:
IndexOfArray是在類上定義的靜態方法。由于您的代碼不是該類的一部分,因此您需要在其前面加上類名,就像您在第二次嘗試中所做的那樣:
Array.IndexOf(Alarm_Names, code)
除此之外,您的代碼中唯一的編譯器錯誤是該Alarm_Names欄位中缺少分號。
修復該問題后,您的代碼將編譯(除非代碼中未顯示的部分出現其他錯誤)。
using System; // needed for accessing "Array"
class YourClass
{
static string[] Alarm_Names = new string[3] {"A1", "A2", "A3"};
static bool[] arr_Alarms = new bool[3] {false, false, false};
internal static void HandleAlarm(..., string code, ...)
{
if (arr_Alarms[Array.IndexOf(Alarm_Names, code)]) return;
如果它仍然無法編譯,您需要列出您遇到的實際編譯器錯誤。
注意:如果您使用的是 C# 6 或更高版本,則可以使用該using static功能使類的所有static成員都Array可以在沒有Array.前綴的情況下呼叫:
using static System.Array;
class YourClass
{
static string[] Alarm_Names = new string[3] {"A1", "A2", "A3"};
static bool[] arr_Alarms = new bool[3] {false, false, false};
internal static void HandleAlarm(..., string code, ...)
{
if (arr_Alarms[IndexOf(Alarm_Names, code)]) return;
靜態修飾符 | 使用指令 | C# 參考
uj5u.com熱心網友回復:
static void Main(string[] args)
{
string[] Alarm_Names = new string[3] { "A1", "A2", "A3" };
bool[] arr_Alarms = new bool[3] { false, false, false };
Console.WriteLine(HandleAlarm(arr_Alarms, "A2", Alarm_Names));
Console.ReadKey();
}
static bool HandleAlarm(bool[] a, string code, string[] A)
{
if (a[Array.IndexOf(A, code)])//false
{
return a[Array.IndexOf(A, code)];
}
return true;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/414358.html
標籤:
下一篇:字串拆分c#但忽略某些情況
