2014-01-26 41 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

我很高兴你找到了一个可行的解决方案。祝你好运! –