How do I get the value of MemberInfo?

后端 未结 3 711
感情败类
感情败类 2021-02-11 14:40

How do I get the value of a MemberInfo object? .Name returns the name of the variable, but I need the value.

I think you can do this with

3条回答
  •  清歌不尽
    2021-02-11 15:19

    Although I generally agree with Marc's point about not reflecting fields, there are times when it is needed. If you want to reflect a member and you don't care whether it is a field or a property, you can use this extension method to get the value (if you want the type instead of the value, see nawful's answer to this question):

        public static object GetValue(this MemberInfo memberInfo, object forObject)
        {
            switch (memberInfo.MemberType)
            {
                case MemberTypes.Field:
                    return ((FieldInfo)memberInfo).GetValue(forObject);
                case MemberTypes.Property:
                    return ((PropertyInfo)memberInfo).GetValue(forObject);
                default:
                    throw new NotImplementedException();
            }
        } 
    

提交回复
热议问题