传递属性静态数组 [英] Passing static array in attribute

查看:126
本文介绍了传递属性静态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能规避以下限制:

Is it possible to circumvent the following restriction:

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

Create a static readonly array in a class:

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

然后它作为参数传递到属性:

Then pass it as a parameter to an attribute:

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

    FooAttribute()
    {
    }
}

---比方说,箱子是A类的属性---

--- Let's say Box is a property of class A ---

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

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

I know this won't compile and will result in this error:

的属性参数必须是常量前pression的typeof
  一个属性参数的前pression或数组创建前pression
  键入

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

是否有可能去解决这个莫名其妙地能够使用静态数组?
因为这个我要求将更加方便维修,明智的,因为我有很多的属性。

Is it possible to go around this somehow to be able to use the static array ? I'm asking since this will be much more convenient maintenance-wise, since I have a lot of properties.

先谢谢了。

推荐答案

可惜,这是不可能的。该属性(包括它们的参数值)由编译器放入程序集元数据,因此必须能够在编译时间来评估他们(因此限制不断前pressions;例外的数组创建前pressions显然做,因为否则你不能有数组参数的话)。

Unfortunately this is not possible. The attributes (including the values of their arguments) are placed into the assembly metadata by the compiler so it has to be able to evaluate them at compile time (hence the restriction to constant expressions; the exception for array creation expressions was obviously made because otherwise you could not have array arguments at all).

在此相反,code,实际上初始化 A.Months 仅在运行时执行。

In contrast, the code that actually initializes A.Months is only executed at runtime.

这篇关于传递属性静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆