Check if a property exists in a class

后端 未结 6 1390
面向向阳花
面向向阳花 2020-11-29 03:04

I try to know if a property exist in a class, I tried this :

public static bool HasProperty(this object obj, string propertyName)
{
    return obj.GetType().         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 03:52

    There are 2 possibilities.

    You really don't have Label property.

    You need to call appropriate GetProperty overload and pass the correct binding flags, e.g. BindingFlags.Public | BindingFlags.Instance

    If your property is not public, you will need to use BindingFlags.NonPublic or some other combination of flags which fits your use case. Read the referenced API docs to find the details.

    EDIT:

    ooops, just noticed you call GetProperty on typeof(MyClass). typeof(MyClass) is Type which for sure has no Label property.

提交回复
热议问题