I want to call Type.GetFields() and only get back fields declared as "public const". I have this so far...
type.GetFields(BindingFlags.Static | BindingFlags.Public)
... but that also includes "public static" fields.
type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.IsLiteral);
Trying checking whether FieldInfo.Attributes
includes FieldAttributes.Literal
. I haven't checked it, but it sounds right...
(I don't think you can get only constants in a single call to GetFields
, but you can filter the results returned that way.)
Starting from .NET 4.5 you can do that
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);
}
}
I checked and it looks like fields has all private consts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With