c# - 按名称选择一个类字段,就好像它是一本字典?

标签 c#

我有一个函数可以通过选定的字段过滤特定类的对象。我目前这样做的方式是将命名该字段的字符串作为参数传递给函数。理想情况下,我希望能够使用此字符串来选择对象中的字段,类似于字典(例如,此功能存在于 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);
 }

enter image description here

或者也许是一种使生活更轻松的扩展方法:

    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/

相关文章:

c# - TeamCity 在构建项目时包含 dll 作为引用

c# - 奇怪的行为 : Catching ThreadAbortException and throwing different exception

c# - WPF/XAML 中 Canvas 中的可重复形状

c# - 如何在 ASP.NET C# 应用程序中使用 SSL

c# - 如何在 .NET 中不使用乘法运算符实现乘法

c# - 在 Fluent NHibernate 中自动截断字符串

c# - DataGridComboBoxColumn ActionHandler

c# - VB6:如何创建 DLL 并在 C# 中使用它?

c# - Azure函数应用程序、服务总线和返回服务总线

c# - Asp.Net 标识 : invalid_request on redirect when calling REST function GetExternalLogin