2009-10-21 92 views
3

是否有一種方法可以使用Property從字符串數組中獲取特定元素(基於索引)。我更喜歡使用公共屬性來取代公開的字符串數組。我在C#.NET 2.0使用屬性獲取C#中的數組元素

問候

回答

6

如果我正確理解你在問什麼,你可以使用索引器。 Indexers (C# Programming Guide)

編輯:現在我讀了其他的,也許你可以公開一個屬性,返回數組的副本?

+0

我不想返回整個字符串數組的副本,只是數組的一個元素。我認爲索引會有所幫助。謝謝 – kobra 2009-10-21 21:32:43

4

工作如果財產公開數組:

string s = obj.ArrayProp[index]; 

如果你的意思是「我能有一個索引屬性」,則沒有 - 但你可以有屬性是一個索引器類型:

static class Program 
{ 
    static void Main() 
    { 
     string s = ViaArray.SomeProp[1]; 
     string t = ViaIndexer.SomeProp[1]; 
    } 
} 
static class ViaArray 
{ 
    private static readonly string[] arr = { "abc", "def" }; 
    public static string[] SomeProp { get { return arr; } } 
} 
static class ViaIndexer 
{ 
    private static readonly IndexedType obj = new IndexedType(); 
    public static IndexedType SomeProp { get { return obj; } } 
} 
class IndexedType 
{ 
    private static readonly string[] arr = { "abc", "def" }; 
    public string this[int index] 
    { 
     get { return arr[index]; } 
    } 
} 
+0

對不起,我的意思是類似於公共字符串[]名稱{得到{返回_名稱[索引]; }} – kobra 2009-10-21 21:22:47

3

你需要的是一個可以有輸入(一個索引)的屬性。

只有一個這樣的屬性,稱爲索引器。

在MSDN上查找它。

快捷鍵:使用內置的代碼片段:轉到您的班級並鍵入'indexer',然後按兩次選項卡。中提琴!

1

我假設你有一個具有私有字符串數組的類,並且你希望能夠獲取數組的一個元素作爲你的類的屬性。

public class Foo 
{ 
    private string[] bar; 

    public string FooBar 
    { 
     get { return bar.Length > 4 ? bar[4] : null; } 
    } 
} 

這似乎可怕的哈克,雖然如此,我現在不是不明白你想要什麼,或者可能有一個更好的方式做你想做的,但我們需要知道更多的信息。

更新:如果您在註釋中指明瞭某個元素的索引,那麼可以使用索引器或簡單地創建一個獲取索引並返回該值的方法。我會保留一個本身就是一個容器的類的索引器,否則使用方法路由。

public string GetBar(int index) 
{ 
    return bar.Length > index ? bar[index] : null; 
} 
+0

我可以看到從預構建的CSV解析器返回的字符串數組,並且想構建一個簡單的對象來包裝該數組的內容。但將字符串複製到支持商店可能更好,因爲它們只是引用。 – 2009-10-21 21:25:37

+0

對不起,如果我困惑你。我真的想要使用另一個類的字符串數組中的索引來獲取特定元素,而不需要公開字符串數組。所以我想用公共財產。謝謝 – kobra 2009-10-21 21:30:16

0

只需從屬性返回數組;結果對象將表現爲一個數組,因此您可以對其進行索引。

例如爲:

string s = object.Names[15] 
1

屬性不帶參數,這樣就不會成爲可能。

您可以構建一個方法,例如

public string GetStringFromIndex(int i) 
{ 
    return myStringArray[i]; 
} 

,你可能會想要做一些檢查方法。當然,但你的想法。

4

你可能試圖保護原始數組;你的意思是你想要通過「一個財產」(而不是自己的)一個保護性包裝陣列?我正在拍攝這個鏡頭來猜測你的問題的細節。這是一個字符串數組的包裝器實現。數組不能直接訪問,但只能通過包裝器的索引器。

using System; 

public class ArrayWrapper { 

    private string[] _arr; 

    public ArrayWrapper(string[] arr) { //ctor 
     _arr = arr; 
    } 

    public string this[int i] { //indexer - read only 
     get { 
      return _arr[i]; 
     } 
    } 
} 

// SAMPLE of using the wrapper 
static class Sample_Caller_Code { 
    static void Main() { 
     ArrayWrapper wrapper = new ArrayWrapper(new[] { "this", "is", "a", "test" }); 
     string strValue = wrapper[2]; // "a" 
     Console.Write(strValue); 
    } 
}