reflection - .NET 世界中的 "mark a field as literal"是什么意思?

标签 reflection

根据微软的文档,FieldInfo.GetValue(object)会抛出 NotSupportedException如果:

"A field is marked literal, but the field does not have one of the accepted literal types."



我不知道这意味着什么

"mark a field as literal."



我想了解这一点,以便我知道如何防范这种异常。

最佳答案

一个 literalconst field 。每个 const 字段的值都在编译时通过从文字初始化来确定。看看这个代码

using System;
using System.Reflection;


public class Program
{
    const int literal_int = 5;
    readonly int literal_int_two = 5;
    const string literal_string = "Fun";
    const Random literal_random = null;
    int non_literal;

    public static void Main()
    {
        foreach (FieldInfo f in typeof(Program).GetFields(BindingFlags.Instance 
        | BindingFlags.NonPublic
        | BindingFlags.Static
        | BindingFlags.FlattenHierarchy))
        {
            Console.WriteLine("{0} is literal - {1}", f.Name, f.IsLiteral);
            try
            {
                Console.WriteLine("GetValue = {0}", f.GetValue(null));
            }
            catch{}
        }
    }
}

输出:
literal_int is literal - True
GetValue = 5
literal_int_two is literal - False
literal_string is literal - True
GetValue = Fun
literal_random is literal - True
GetValue = 
non_literal is literal - False

然而,

but the field does not have one of the accepted literal types



可以接受解释,我找不到一个没有“一种可接受的文字类型”的文字示例(无论这意味着什么)。

通过简要查看 source code ,我找不到一个相关的代码来代表这个异常。您应该安全地忽略此条款。

关于reflection - .NET 世界中的 "mark a field as literal"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32788026/

相关文章:

java - java 反射的调用方法在该方法发生更改时不会在运行时更新该方法

java - 通过反射获取 super 接口(interface)的泛型类型

java - 使用 MethodHandle 查找最具体的重载方法

c# - 使用 Dynamic 或 Reflection.emit

java - 在 JPA 实体上查找声明的 java.util.Map 字段的泛型类型时出现 ClassNotFoundException (GlassFish 3)

java - 如何检查类的注释是否属于特定类别?

java - 如何获取声明的对象类型的字段?

c# - 有没有办法在 C# 中编写单元测试以确保不会在项目的任何地方调用方法?

c# - 查找程序集中某个类的所有用途

scala - 为什么 Scala "handle"ClassTags 不自动?