gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:06:44 28 4
gpt4 key购买 nike

是否可以规避以下限制:

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com