Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按名称获取常量的值_C#_Field_Constants - Fatal编程技术网

C# 按名称获取常量的值

C# 按名称获取常量的值,c#,field,constants,C#,Field,Constants,我有一个常数类。我有一些字符串,可以和其中一个常量的名称相同,也可以不相同 因此,带有常量ConstClass的类有一些public const像const1、const2、const3… public static class ConstClass { public const string Const1 = "Const1"; public const string Const2 = "Const2"; public const string Const3 = "Co

我有一个常数类。我有一些字符串,可以和其中一个常量的名称相同,也可以不相同

因此,带有常量
ConstClass
的类有一些
public const
const1、const2、const3…

public static class ConstClass
{
    public const string Const1 = "Const1";
    public const string Const2 = "Const2";
    public const string Const3 = "Const3";
}
要检查类是否按名称包含
const
,我已尝试下一步:

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

不知道这样做是否真的正确,但现在我不知道如何获取值,因为
。GetValue
方法需要类型为
ConstClass
(ConstClass是静态的)

的obj来获取字段值或使用传递的反射
null
作为实例引用调用静态类型的成员

下面是一个简短的程序,演示:

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

public class Test
{
    public const int Value = 42;
}
输出:

42
Value
请注意,所示代码不会区分普通字段和常量字段

为此,必须检查字段信息是否也包含标志
Literal

下面是一个仅检索常量的简短LINQPad程序:

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;
}
输出:

42
Value

请您重新组织您的问题,并显示您的代码,以便更容易理解?(不要描述代码,这很难理解)我强烈建议使用
字典
,而不要使用一些常量和反射来获取它们。这更高效,更易维护,也更具可读性。你打算解释你的代码以及它是如何解决这个问题的吗?不,不,不,这是不言自明的。OP询问如何获取常量变量的值,这就是答案;不包含“const”关键字,因此它不是常量变量。因此,无论是否不言自明,这都不是问题的答案。@vynsane,
customStr
包含常量的名称,该名称的值是必需的。这非常有帮助,但我不得不对其进行一些调整,因为我的函数传入了一个
类型
参数。我的实现类似于
(myPassedType作为Type).GetField(“Value”).GetValue(null)