Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c# - Get value of constant by name

I have a class with constants. I have some string, which can be same as name of one of that constants or not.

So class with constants ConstClass has some public const like const1, const2, const3...

public static class ConstClass
{
    public const string Const1 = "Const1";
    public const string Const2 = "Const2";
    public const string Const3 = "Const3";
}

To check if class contains const by name i have tried next :

var field = (typeof (ConstClass)).GetField(customStr);
if (field != null){
    return field.GetValue(obj) // obj doesn't exists for me
}

Don't know if it's realy correct way to do that, but now i don't know how to get value, cause .GetValue method need obj of type ConstClass (ConstClass is static)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get field values or call members on static types using reflection you pass null as the instance reference.

Here is a short LINQPad program that demonstrates:

void Main()
{
    typeof(Test).GetField("Value").GetValue(null).Dump();
    // Instance reference is null ----->----^^^^
}

public class Test
{
    public const int Value = 42;
}

Output:

42

Please note that the code as shown will not distinguish between normal fields and const fields.

To do that you must check that the field information also contains the flag Literal:

Here is a short LINQPad program that only retrieves constants:

void Main()
{
    var constants =
        from fieldInfo in typeof(Test).GetFields()
        where (fieldInfo.Attributes & FieldAttributes.Literal) != 0
        select fieldInfo.Name;
    constants.Dump();
}

public class Test
{
    public const int Value = 42;
    public static readonly int Field = 42;
}

Output:

Value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...