Property hiding and reflection (C#)

前端 未结 3 906
[愿得一人]
[愿得一人] 2020-12-11 00:53

Declaring a property in a derived class that matches the name of a property in the base class \"hides\" it (unless it overrides it with the override keyword).

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 01:19

    I do not think it is possible without traversing the inheritance hierarchy. It does not have to be too much code, though:

        public static IEnumerable GetAllProperties(Type t)
        {
            while (t != typeof(object))
            {
                foreach (var prop in t.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
                    yield return prop;
                t = t.BaseType;
            }
        }
    

    Of course, if you know a common basetype you can stop at, instead of object, it will be more efficient. Also; it will take some time to do the reflection, so cache the result. After all, the type information won't change during execution.

提交回复
热议问题