开发者

C# late bound non exist property

how check is property exist? like

if propertyName in obj
{
}

becau开发者_高级运维se there is some moments when obj doesn't have such property


Another approach using reflection is:

        PropertyInfo info = obj.GetType().GetProperty("PropertyNameToFind");

        if (info != null)
        {
            // Property exists in this type...
        }


Give a look at the System.Reflection.PropertyInfo class.

Here is a sample usage

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜