我有以下代码,
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 .值)
.
问题,有没有办法摆脱辅助方法 GetValue
或类似索引的任何方式,var X = entry.Value[value];
最佳答案
这里有两种方法可以直接添加到类中或者需要使用扩展方法。
我应该提到,如果您的字符串不是属性,这只会引发异常。您需要做一些检查。
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;
}
}
关于c# - 可以通过索引方式获取类属性值或如何摆脱辅助方法 'GetValue',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55217561/