将字符串的值转换为KeyValuePair的变量<tkey,tvalue> </tkey,tvalue>

时间:2012-11-30 12:24:45

标签: c# typeconverter keyvaluepair

我做的是这样的事情:

foreach( KeyValuePair<int,SOME_CLASS> reader in _readerDict )
{
  var selectedReader = reader;

  var antenna1 = selectedReader.Value.Antenna1IsEnabled;
  var antenna2 = selectedReader.Value.Antenna2IsEnabled;
  var antenna3 = selectedReader.Value.Antenna3IsEnabled;
  var antenna4 = selectedReader.Value.Antenna4IsEnabled;
}

但是我又想做以下事情:

foreach( KeyValuePair<int,SOME_CLASS> reader in _readerDict )
{
  var selectedReader = reader;

  for( var idx = 1; idx <= 4; idx++ )
  {
    var antennaIsEnabled = string.Format( "selectedReader.Value.Antenna{0}IsEnabled", idx );

    // cast the value of antennaIsEnabled as a KeyValuePair<int,SOME_CLASS> variable datatype here
    ....
  }
}

我是否仍然将antennaIsEnabled的值转换为KeyValuePair变量数据类型?

3 个答案:

答案 0 :(得分:2)

我想你要提取selectReader为关键字,AntennaIsEnabled为值

string[] parts = strA.Split('.');
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>(part[0], part[2]));

需要添加一些错误检查...

答案 1 :(得分:0)

听起来你想要一个看起来像这样的结果:

Dictionary<int, bool> AntennaIsEnabled = new Dictionary<int, bool>();
foreach( KeyValuePair<int,SOME_CLASS> reader in _readerDict )
{
  var selectedReader = reader;

  //From your example
  AntennaIsEnabled.Add(1, selectedReader.Value.Antenna1IsEnabled);
  AntennaIsEnabled.Add(2, selectedReader.Value.Antenna2IsEnabled);
  AntennaIsEnabled.Add(3, selectedReader.Value.Antenna3IsEnabled);
  AntennaIsEnabled.Add(4, selectedReader.Value.Antenna4IsEnabled);
}

然后,您可以使用AntennaIsEnabled [2]等语法访问每个天线的状态。

答案 2 :(得分:0)

尝试使用 FastMember 库以字符串形式访问您的媒体资源。