在 .NET 的世界中,"mark a field as literal" 意味着什么?

What does it mean to "mark a field as literal" in the world of .NET?

根据 Microsoft 的文档,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."

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

看看 FieldInfo.IsLiteral Property:

Gets a value indicating whether the value is written at compile time and cannot be changed.

The IsLiteral property is set when the FieldAttributes.Literal attribute is set. If this attribute is set, the field cannot be changed and is constant.

一个literal是一个const字段。每个 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

可以解释,我找不到没有 'one of the accepted literal types' 的文字示例(无论那是什么意思)。

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

所述的异常

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

... 必须与动态或自定义代码创建的 FieldInfo 个实例相关(而不是通过 Reflection 收集),其中某些验证通常会延迟或省略.

FieldInfo 对象包含表示字段的元数据,但其 class 是可继承的,任何派生的实现都可能允许错误的类型条件。