简体   繁体   English

通过反射.NET获取静态属性

[英]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). 这里propInf为null(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. 正如注释中指定的@JeroenVanLangen一样,您定义了字段而不是属性。 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. @Edit:正如Jeppe Stig Nielsen在评论中指出的那样,每次访问该属性时,都会对所提出的第一个解决方案进行评估。 To avoid this, and simply have it preserve the value in the property itself, use: 为了避免这种情况,并简单地使其保留属性本身中的值,请使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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