简体   繁体   中英

Get static property through reflection .NET

I've seen this answered already, but it hasn't worked for me. I'm trying to access a (non-static) class static property from the base class, from an derived instance.

In the base class:

Type type = this.GetType();
PropertyInfo propInf = type.GetProperty("DirectoryCode", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

Here propInf is null (type is the derived class type).

In the derived class:

public class DTGCSMissonParameters : ModelBase
{
   public static ushort DirectoryCode = (ushort) DIR.MISSION_PARAMETERS;

Thanks

As @JeroenVanLangen specified in the comments, you defined a Field instead of a Property. The correct statement should be:

// C# 6.0
public static ushort DirectoryCode => (ushort) DIR.MISSION_PARAMETERS;

// Pre-C# 6.0
public static ushort DirectoryCode
{ 
     get { return (ushort) DIR.MISSION_PARAMETERS; }
}

@Edit: As Jeppe Stig Nielsen pointed out in the comments, the first of the proposed solutions would be evaluated every time the property was accessed. To avoid this, and simply have it preserve the value in the property itself, use:

public static ushort DirectoryCode { get; } = (ushort) DIR.MISSION_PARAMETERS;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM