【问题标题】:Get object properties with reflection except instance properties使用反射获取对象属性,实例属性除外
【发布时间】:2014-03-17 10:15:56
【问题描述】:

我想使用反射枚举所有对象属性,但我想排除引用对象的属性(这应该足够快,因为我在使用 Redis/Booksleve 的缓存解决方案中使用)。

目前我有以下内容,但这会返回所有对象属性,包括实例成员:

var propertyNameAndValues = member.GetType().GetProperties().Where(m => m.GetGetMethod() != null).ToDictionary(i => i.Name, i => Encoding.UTF8.GetBytes(i.GetGetMethod().Invoke(member, null).ToString()));
var task = conn.Hashes.Set(db, string.Format("members:{0}", member.id), propertyNameAndValues);

【问题讨论】:

    标签: c# reflection booksleeve getproperties


    【解决方案1】:

    使用overload of GetProperties 可以指定BindingFlags 参数并确保包含BindingFlags.Static 但排除BindingFlags.Instance

    例如:

    var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
    var properties = member.GetType().GetProperties(flags);
    

    【讨论】:

    • 你忘了传递标志
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2012-06-22
    相关资源
    最近更新 更多