Check if a property exists in a class

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

    This answers a different question:

    If trying to figure out if an OBJECT (not class) has a property,

    OBJECT.GetType().GetProperty("PROPERTY") != null
    

    returns true if (but not only if) the property exists.

    In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.

    @if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
            Model.AddTimeoffBlackouts)
    

    helped me here.

    Edit: Nowadays, it's probably smart to use the nameof operator instead of the stringified property name.

提交回复
热议问题