Check if a property exists in a class

后端 未结 6 1404
面向向阳花
面向向阳花 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:41

    Your method looks like this:

    public static bool HasProperty(this object obj, string propertyName)
    {
        return obj.GetType().GetProperty(propertyName) != null;
    }
    

    This adds an extension onto object - the base class of everything. When you call this extension you're passing it a Type:

    var res = typeof(MyClass).HasProperty("Label");
    

    Your method expects an instance of a class, not a Type. Otherwise you're essentially doing

    typeof(MyClass) - this gives an instanceof `System.Type`. 
    

    Then

    type.GetType() - this gives `System.Type`
    Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type`
    

    As @PeterRitchie correctly points out, at this point your code is looking for property Label on System.Type. That property does not exist.

    The solution is either

    a) Provide an instance of MyClass to the extension:

    var myInstance = new MyClass()
    myInstance.HasProperty("Label")
    

    b) Put the extension on System.Type

    public static bool HasProperty(this Type obj, string propertyName)
    {
        return obj.GetProperty(propertyName) != null;
    }
    

    and

    typeof(MyClass).HasProperty("Label");
    

提交回复
热议问题