Question:
How do I get all public properties of a given type as a Dictionary?How do I get properties of an object?
Get list of ProperyInfo for a given type.
Answer:
Use the System.Reflection namespace.Follow these steps:
- Get the type directly or from the object by obj.GetType()
- Get the public properties.
- Fill the dictionary.
Here is an example
using System.Reflection; ... // 1) Type sourceType = typeof(MyType); // 2) PropertyInfo[] pList = sourceType.GetProperties(); Dictionary<string, PropertyInfo> _propertyDico = new Dictionary<string, PropertyInfo>(); // 3) pList.ToList>PropertyInfo<().ForEach(pInfo=> _propertyDico.Add(pInfo.Name, pInfo));
Remark: Type.GetProperties() gets all public properties by default.
If you want to filter more precisely, you must pass BindingFlags when calling GetProperties method.
PropertyInfo[] propertyInfos = propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Static);
No comments:
Post a Comment