2014-01-26 42 views
1

我目前通過此方法設置一些字符串:C#訪問一個方法值動態地使用字符串

string marketlabel = [email protected](); 

我想通過具有用於實際的市場選擇一個字符串動態地設置市場標籤。

string currentMarketSelected= this.marketTextBox.Text; // Specific market: COLXPM 

string [email protected]label.ToString(); 

我一直在尋找幾個小時,可能沒有正確解釋。我嘗試了一些沒有成功的思考。基本上我想要做的是有一個文本框或列表,其中包含所有的市場名稱和基於哪一個被選擇開始設置數據。

以上是我想要做的最好的例子類型,儘管它在語法上不可能在位置上使用變量。

public class Markets 
{ 
    public COLXPM COLXPM { get; set; } 
    //Lots of markets below here 
} 

public class COLXPM 
{ 
    public string marketid { get; set; } 
    public string label { get; set; } 
    public string lasttradeprice { get; set; } 
    public string volume { get; set; } 
    public string lasttradetime { get; set; } 
    public string primaryname { get; set; } 
    public string primarycode { get; set; } 
    public string secondaryname { get; set; } 
    public string secondarycode { get; set; } 
    public List<Recenttrade> recenttrades { get; set; } 
    public List<Sellorder> sellorders { get; set; } 
    public List<Buyorder> buyorders { get; set; } 
} 
public class Return 
{ 
    public Markets markets { get; set; } 
} 

public class RootObject 
{ 
    public int success { get; set; } 
    public Return @return { get; set; } 
} 

低於所提出的解決方案工作

string currentMarketSelected = "DOGEBTC"; // Just selecting one of the markets to test it works 
var property = [email protected]().GetProperty(currentMarketSelected); 
dynamic market = property.GetMethod.Invoke([email protected], null); 
string marketlabel = market.label.ToString(); //Gets all my selected market data 
+0

如果您不知道您正在使用哪些課程,我們無法幫助您。那些看起來完全陌生。 –

+0

刪除~~~~~~~~~ – juju

+0

「allmarketdata。@ return.markets」,會不會編譯? – Voice

回答

1

這是一個使用反射的解決方案。

string currentMarketSelected= this.marketTextBox.Text; // Specific market: COLXPM 

var property = [email protected]().GetProperty(currentMarketSelected); 
dynamic market = property.GetGetMethod().Invoke([email protected], null); 
string marketlabel=market.label.ToString(); 
+0

只是爲了測試它的工作原理,我嘗試了數據結構中的其他市場之一,它工作得很好。我必須將其從allmarketdata移到一個@ @ return to allmarketdata。@ return.markets – juju

+0

我相應地修復了發佈的解決方案。 – wdosanjos

0

你需要的東西是這樣的:

public class Markets 
{ 
    public COLXPM this[string key] 
    { 
     get 
     { 
      COLXPM colxpm; 

      switch (key) 
      { 
       // TODO : use "key" to select instance of COLXPM; 
       case "example1": 
        colxpm = ...; 
        break; 

       default: 
        throw new NotSupportedException(); 
      } 

      return colxpm; 
     } 
    } 
} 

然後,你可以這樣做:

string [email protected][currentMarketSelected]label.ToString(); 

這是一個索引屬性。

+0

只要我可以測試一下,我會盡快回復。 – juju

+0

我相信這種方法的工作原理,我避免了它,我將不得不更新大約92定義,以包括您在上面添加的邏輯很多。 – juju

+0

我很高興你找到了一個可行的解決方案。祝你好運! –