如何检查属性存在?像
if propertyName in obj
{
}
因为有些时候obj没有这样的属性
答案 0 :(得分:4)
使用反射的另一种方法是:
PropertyInfo info = obj.GetType().GetProperty("PropertyNameToFind");
if (info != null)
{
// Property exists in this type...
}
答案 1 :(得分:1)
查看System.Reflection.PropertyInfo课程。
以下是示例用法
using System.Reflection; // reflection namespace
// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos, delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
{ return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
// write property names
foreach (PropertyInfo propertyInfo in propertyInfos) {
Console.WriteLine(propertyInfo.Name);
}