Csharp/C#教程:Type.GetFields() – 仅返回“public const”字段分享


Type.GetFields() – 仅返回“public const”字段

我想调用Type.GetFields()并只返回声明为“public const”的字段。 到目前为止我有这个…

type.GetFields(BindingFlags.Static | BindingFlags.Public) 

……但这也包括“公共静态”字段。

尝试检查FieldInfo.Attributes是否包含FieldAttributes.Literal 。 我没有检查过,但听起来不错……

(我不认为你只能GetFields的一次调用中获得常量 ,但是你可以过滤那种返回的结果。)

 type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.IsLiteral); 

从.NET 4.5开始,您可以做到这一点

 public class ConstTest { private const int ConstField = 123; public int GetValueOfConstViaReflection() { var fields = this.GetType().GetRuntimeFields(); return (int)fields.First(f => f.Name == nameof(ConstField)).GetValue(null); } } 

我查了一下,看起来田野里有所有的私人景点。

上述就是C#学习教程:Type.GetFields() – 仅返回“public const”字段分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/960998.html

(0)
上一篇 2021年11月25日
下一篇 2021年11月25日

精彩推荐