【问题标题】:.NET - Whitelisting properties to anonymous object.NET - 将属性列入匿名对象的白名单
【发布时间】:2016-09-17 17:27:57
【问题描述】:

我想根据现有对象和白名单动态创建匿名对象。

例如我有以下课程:

class Person
{
    string FirstName;
    string LastName;
    int Age;
}

现在我已经创建了一个函数 FilterObject 来根据 whitelist 参数创建一个新的匿名 obj,如下所示:

public static class Filter
{
    public static object FilterObject(Person input, string[] whitelist)
    {
        var obj = new {};

        foreach (string propName in whitelist)
            if (input.GetType().GetProperty(propName) != null)
                // Pseudo-code:
                obj.[propName] = input.[propName];

        return obj;
    }
}

// Create the object:
var newObj = Filter.FilterObject(
    new Person("John", "Smith", 25), 
    new[] {"FirstName", "Age"});

结果应该如下所示。我想将此对象用于我的 Web API。

var newObj = new
{
    FirstName = "John",
    Age = 25
};

有什么办法可以做到吗?

【问题讨论】:

    标签: c# .net types properties casting


    【解决方案1】:

    您可以尝试使用ExpandoObject(.net 4 或更高版本):

    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
    
    static class Filter
    {
        public static object FilterObject(Person input, string[] whitelist)
        {
            var o = new ExpandoObject();
            var x = o as IDictionary<string, object>;
    
            foreach (string propName in whitelist)
            {
                var prop = input.GetType().GetProperty(propName);
    
                if (prop != null)
                {
                    x[propName] = prop.GetValue(input, null);
                }
            }
    
            return o;
        }
    }
    

    这只是基于您的代码的示例,但它是一个很好的起点。

    【讨论】:

      【解决方案2】:

      使用字典怎么样?

      public static object FilterObject(Person input, string[] whitelist)
      {
          var obj = new Dictionary<string, object>();
      
          foreach (string propName in whitelist)
          {
              var prop = input.GetType().GetProperty(propName);
      
              if(prop != null)
              {
                  obj.Add(propName, prop.GetValue(input, null));
              }
          }               
      
          return obj;
      }
      

      另外,你真的需要返回一个对象吗?因为如果您总是检查 Person 类型中存在的白名单中的属性,为什么不返回 Person 类的实例呢?

      【讨论】:

      • 它应该是一个对象,因为我想将它用于 Web API。
      • 您是否担心会在 Person 类中得到“空”属性?您可以轻松解决这个问题。
      猜你喜欢
      • 2017-01-02
      • 2021-02-28
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多