【问题标题】:Generic method to return Dictionary for all its property为所有属性返回 Dictionary 的通用方法
【发布时间】:2013-05-14 23:54:55
【问题描述】:

我想编写一个泛型方法,它接受任何类型的类对象,并为该对象的所有属性返回一个 keyValuepair。

public Dictionary<string,string> GetProperties(T classObj)
{
}

对此的任何帮助将非常有用。

【问题讨论】:

标签: c# .net c#-4.0


【解决方案1】:

使用反射:

public Dictionary<string, object> GetProperties<T>(T classObj)
{
    return typeof(T).GetProperties()
            .ToDictionary(p => p.Name, p => p.GetValue(classObj, null));
}

【讨论】:

  • 你不需要在这里使用泛型 - object classObj 就足够了。此外,使用typeof(T),如果您提供了GetProperties&lt;BaseClass&gt;,但传递了一个扩展BaseClass 的对象,则可能会错过属性,因此请改用classObj.GetType()
猜你喜欢
  • 2021-08-22
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
  • 2010-09-25
  • 2022-01-26
  • 2012-07-06
相关资源
最近更新 更多