2013-02-19 86 views
-2

如何聲明索引屬性?什麼是在C#索引一個屬性的正確語法

public class PublishProperties : ScriptableObject { 

List<string> m_shellPathsT = new List<string>(); 
List<string> m_shellPathsL = new List<string>(); 
public List<string> ShellPath[int index] 
{ 
    get 
    { 
     if (index == 0) 
      return m_shellPathsT; 
     else 
      return m_shellPathsL; 
    } 
} 

這不會編譯,我不知道如何編碼。由於其他要求,我必須擁有兩個不同的列表,這些列表都是這樣聲明的。

我通常會具有一個列表的數組...

或類似這樣的

public List<string>[] m_shellPaths = { new List<string>(), new List<string>() }; 

然而,這又沒有其他因素的工作......(基本上有一些系列化出現這種情況自動不與構造函數或像上述聲明的變量工作)。

+0

我說得沒錯,你是否試圖爲自己的班級創建索引訪問? – bash0r 2013-02-19 23:35:35

+0

http://msdn.microsoft.com/en-us/library/vstudio/6x16t2tx.aspx你需要將屬性更改爲公共字符串this [int i] – 2013-02-19 23:36:50

+1

你只能創建一個索引器(比如'string this [int index ]'),你不能建立索引屬性。爲了達到這個目的,只需將'ShellPath'的類型實現爲'this [int]' – millimoose 2013-02-19 23:36:52

回答

1

Please read the docs before asking questions.

public List<string> this[int index] 
{ 
    get 
    { 
     if (index == 0) 
      return m_shellPathsT; 
     else 
      return m_shellPathsL; 
    } 
} 
+0

如果我們有List m_shellPathsT比indexer應該返回簡單的字符串嗎? – 2013-02-19 23:38:13

+0

@AndriyKhrystyanovich原始代碼返回列表。 – wRAR 2013-02-19 23:38:58

+0

@wRAR我簡化了代碼並閱讀了文檔...這不是我所需要的。我需要在類中索引數組而不是類本身... – vbbartlett 2013-02-19 23:45:17

0

C#不支持索引屬性。您可以使用索引

public List<string> this[int index] 
{ 
    get 
    { 
     if (index == 0) 
      return m_shellPathsT; 
     else 
      return m_shellPathsL; 
    } 
} 

但在這個非常特殊的情況下,我無法因爲需要幾套這種類型的實現做這樣和系列化阻止我用更優雅的聲明類本身。

可以使用方法,但不具有與屬性相同的功能。
我對此發現了更多information

然而在這情況下,沒有理由我不能添加額外的陣列

public List<string> m_shellPathsT = new List<string>(); 
public List<string> m_shellPathsL = new List<string>() ; 
public List<string>[] m_shellPaths = new List<string>[2]; 

public PublishProperties() 
{ 
    m_shellPaths[0] = m_shellPathsT; 
    m_shellPaths[1] = m_shellPathsL; 
} 
0

根據您的意見,似乎要通過ShellPaths訪問的任何m_shellPathsTm_shellPathsS項目。

因此,假設foo是PublishProperties類型的對象,你希望能夠寫出這樣的代碼:

foo.ShellPaths[0]; 

這裏會發生什麼事其實​​是兩件事情:

  1. 您正在訪問物業ShellPaths在類型PublishProperties。它返回List<string>
  2. 您正在訪問返回列表的索引0處的項目。它返回一個string

酒店ShellPaths具有以下結構:

public List<string> ShellPaths 
{ 
    get { return <something>; } 
} 

正如你所看到的,沒有索引。

但是由於您想根據索引訪問不同的列表,所以ShellPaths的實現不能簡單地返回任何一個內部存儲的列表。

如果索引爲0,則必須創建一個新列表,返回m_shellPathsT的第一項。否則,它會返回m_shellPathsS的相應項目。

要做到這一點,你可以實現ShellPaths這樣的:

public List<string> ShellPaths 
{ 
    get { return m_shellPathsT.Take(1).Concat(m_shellPathsS.Skip(1)).ToList(); } 
} 

現在,將工作,但將是非常效率不高:每次有人訪問ShellPaths創建一個新的列表。如果您想創建特殊列表一次,可能在構造函數中或任何內部列表的內容發生更改時更好。

相關問題