我有以下代码,
var data = new Dictionary<string, TestData>
{
{ "A1", new TestData { Name = "N1", Section = "S1" } },
{ "A2", new TestData { Name = "N2", Section = "S2" } }
};
var strArray = new string[2] { "Name", "Section" };
foreach (KeyValuePair<string, TestData> entry in data)
{
foreach (string value in strArray)
{
var X = GetValue(value, entry.Value);
}
}
private static string GetValue(string value, TestData data)
{
string val = string.Empty;
if(value == "Name")
{
val = data.Name;
}
if (value == "Section")
{
val = data.Section;
}
return val;
}
这里的类属性和字符串数组的名称分别为Name
和Section
,而我正在使用一些小的辅助方法来获取类属性值GetValue(value, entry.Value)
。
问题,有没有办法摆脱助手方法GetValue
或诸如索引var X = entry.Value[value];
之类的任何方式
答案 0 :(得分:1)
有两种方法可以将其直接添加到类中,还是需要使用扩展方法。
我应该提到,如果您的字符串不是属性,这只会引发异常。您需要进行一些检查。
public class TestData
{
public string Name { get; set; }
public string Section { get; set; }
public string Value(string value)
{
var val = typeof(TestData).GetProperty(value).GetValue(this);
// This will return null instead of throwing an exception
// var val = typeof(TestData).GetProperty(value)?.GetValue(this);
if (val is string result)
{
return result;
}
return default;
}
}
或使用扩展方法
public static class TestDataExtensions
{
public static string Value(this TestData testData, string value)
{
var val = typeof(TestData).GetProperty(value).GetValue(testData);
if (val is string result)
{
return result;
}
return default;
}
}
答案 1 :(得分:1)
反射方法缺少.Value
:
var entryName = entry.Value.GetType().GetProperty("Name").GetValue(entry.Value, null);
var entrySection = entry.Value.GetType().GetProperty("Section").GetValue(entry.Value, null);
答案 2 :(得分:1)
适用于所有类型。
'\\n'
答案 3 :(得分:0)
使用Reflection:
var entryName = entry.Value.GetType().GetProperty("Name").GetValue(entry.Value, null);
var entrySection = entry.Value.GetType().GetProperty("Section").GetValue(entry.Value, null);
因此在您的代码中将是:
foreach (KeyValuePair<string, TestData> entry in data)
{
var entryName = entry.Value.GetType().GetProperty("Name").GetValue(entry.Value, null);
var entrySection = entry.Value.GetType().GetProperty("Section").GetValue(entry.Value, null);
}
答案 4 :(得分:0)
您可以使用反射来获取所有属性的列表,并像这样遍历它们:
var properties = typeof(TestData).GetProperties();
foreach (KeyValuePair<string, TestData> entry in data)
{
foreach (var propertyInfo in properties)
{
var X = propertyInfo.GetValue(entry.Value);
}
}