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.
所以类 ConstClass 有一些 public const 比如 const1, const2, const3...
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";
}
为了检查类是否包含 const 我已经尝试过下一步:
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
}
不知道这样做是否真的正确,但现在我不知道如何获取值,因为 .GetValue 方法需要 ConstClass(ConstClass 是静态的)
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)
推荐答案
要使用反射获取字段值或调用静态类型的成员,您需要传递 null 作为实例引用.
To get field values or call members on static types using reflection you pass null as the instance reference.
这是一个简短的 LINQPad 程序,演示:
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;
}
输出:
42
请注意,显示的代码不会区分普通字段和常量字段.
Please note that the code as shown will not distinguish between normal fields and const fields.
为此,您必须检查字段信息是否还包含标志 Literal:
To do that you must check that the field information also contains the flag Literal:
这是一个只检索常量的简短 LINQPad 程序:
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;
}
输出:
Value
这篇关于按名称获取常量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按名称获取常量的值
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
