c# - 在属性中传递静态数组

标签 c# static attributes

是否可以规避以下限制:

在类中创建静态只读数组:

public class A
{
    public static readonly int[] Months = new int[] { 1, 2, 3};
}

然后将其作为参数传递给属性:

public class FooAttribute : Attribute
{
    public int[] Nums { get; set; }

    FooAttribute()
    {
    }
}

--- 假设 Box 是类 A 的属性 ---

[Foo(Nums = A.Months)]
public string Box { get; set; }

我知道这不会编译并会导致这个错误:

"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type".

是否有可能以某种方式解决这个问题以便能够使用静态数组? 我问是因为这在维护方面会方便得多,因为我有很多属性。

提前致谢。

最佳答案

不幸的是,这是不可能的。属性(包括它们参数的值)由编译器放入程序集元数据中,因此它必须能够在编译时评估它们(因此对常量表达式的限制;数组创建表达式的异常(exception)显然是因为否则你根本不能有数组参数)。

相比之下,真正初始化A.Months的代码只在运行时执行。

关于c# - 在属性中传递静态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16710533/

相关文章:

c# - C# 中的 VBScript 错误处理

java - Java中的类加载时间

python - 该对象在 Django 中没有属性 'is_hidden'

java - 获取组件标签的属性值

c# - 单元测试 NotifyPropertyChanged()

C# linq order by 和 take

c# - 异步运行存储过程

android - Android 中的 IllegalStateException

c - C中数组的理想数据类型

javascript - 如何避免将 JavaScript 与 CSS 属性选择器一起使用