我有一个函数可以通过选定的字段过滤特定类的对象。我目前这样做的方式是将命名该字段的字符串作为参数传递给函数。理想情况下,我希望能够使用此字符串来选择对象中的字段,类似于字典(例如,此功能存在于 javascript 中)。
所以我在这里有函数(减少到相关位):
private List<HangingArtBundle> ConstrainBundlesBy(List<HangingArtBundle> bundles, string valueString, string constraint)
{
List<HangingArtBundle> retBundles = new List<HangingArtBundle>();
List<string> values = new List<string>(valueString.Split(new char[] { '|' }));
foreach (HangingArtBundle bundle in bundles)
{
if (values.Contains(ConstrainedField(constraint, bundle)))
{
retBundles.Add(bundle);
}
}
return retBundles;
}
我希望能够用 bundle[constraint]
之类的东西替换 ConstrainedField(constraint, bundle)
部分,其中 constraint
是类 HangingArtBundle
的字段名称。相反,我必须使用下面的这个功能,这需要我根据需要手动添加字段名称:
private string ConstrainedField(string field, HangingArtBundle bundle)
{
if (field.Equals("Category"))
{
return bundle.Category;
}
else if (field.Equals("AUToolTab"))
{
return bundle.AUToolTab;
}
else
{
return "";
}
}
如果有帮助的话,这里是类(本质上只是一个结构):
public class HangingArtBundle
{
public string CP { get; set; }
public string Title { get; set; }
public string Category { get; set; }
public string AUToolTab { get; set; }
public List<HangingArtEntry> Art { get; set; }
}
这可以用 C# 优雅的方式完成吗?
最佳答案
为此你可以使用 System.Reflection
private string GetField(HangingArtBundle hab, string property)
{
return (string)hab.GetType().GetProperty(property).GetValue(hab, null);
}
或者也许是一种使生活更轻松的扩展方法:
public static class Extensions
{
public static string GetField(this HangingArtBundle hab, string property)
{
if (hab.GetType().GetProperties().Any(p => p.Name.Equals(property)))
{
return (string)hab.GetType().GetProperty(property).GetValue(hab, null);
}
return string.Empty;
}
}
用法:
string result = bundle.GetField("CP");
关于c# - 按名称选择一个类字段,就好像它是一本字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13695098/