簡體   English   中英

C#獲取訪問器無法訪問

[英]C# Get accessor is inaccessible

我有以下類定義:

 public static string SplitString(string someText)
 {
      var queryArray = Regex.Split(someText, "\\s+(?=\\w+)");
      foreach (var i in Enumerable.Range(0, queryArray.Count - 1)) {
           // Some code
      }
 }

問題是queryArray.Count給我以下錯誤:

在這種情況下,不能使用屬性'System.Array.Count',因為無法訪問get訪問器。

我在這里想念什么?

您可以嘗試改用Length屬性:

public static string SplitString(string someText)
{
    var queryArray = Regex.Split(someText, "\\s+(?=\\w+)");
    foreach (var i in Enumerable.Range(0, queryArray.Length - 1)) {
        // Some code
    }
}

同樣,如果這樣編寫,您的代碼可能更易讀:

public static string SplitString(string someText)
{
    var queryArray = Regex.Split(someText, "\\s+(?=\\w+)");
    for (var i = 0; i < queryArray.Length; i++) {
        // Some code
    }
}

或像這樣:

public static string SplitString(string someText)
{
    var queryArray = Regex.Split(someText, "\\s+(?=\\w+)");
    foreach (var item in queryArray) {
        // Some code
    }
}

Regex.Split返回一個數組,該數組未定義Count屬性。 使用Length代替:

 public static string SplitString(string someText)
 {
      var queryArray = Regex.Split(someText, "\\s+(?=\\w+)");
      foreach (var i in Enumerable.Range(0, queryArray.Length - 1)) {
           // Some code
      }
 }

您可以嘗試使用Length property

當Select擴展為您提供索引時,為什么還要擔心索引:

var data = Regex.Split("someText other", "\\s+(?=\\w+)")
                .Select((itm, indexer) => string.Format("{0} is index {1}", itm, indexer));

/* Data has 2 strings in the list:

someText is index 0
other is index 1

*/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM