在属性中传递静态数组

Omr*_*ron 9 c# static attributes

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

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

public class A
{
    public static readonly int[] Months = new int[] { 1, 2, 3};
}
Run Code Online (Sandbox Code Playgroud)

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

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

    FooAttribute()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

---让我们说Box是A级的属性---

[Foo(Nums = A.Months)]
public string Box { get; set; }
Run Code Online (Sandbox Code Playgroud)

我知道这将无法编译,并将导致此错误:

"属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式".

有可能以某种方式解决这个问题,以便能够使用静态数组吗?我问,因为我有很多属性,所以维护方面会更方便.

提前致谢.

Mar*_*ell 10

不,基本上.

但是,您可以将该属性子类化并使用它,即

class AwesomeFooAttribute : FooAttribute {
    public AwesomeFooAttribute() : FooAttribute(A.Months) {}
}
Run Code Online (Sandbox Code Playgroud)

要么:

class AwesomeFooAttribute : FooAttribute {
    public AwesomeFooAttribute() {
        Nums = A.Months;
    }
}
Run Code Online (Sandbox Code Playgroud)

[AwesomeFoo]改为装饰.如果您使用反射来查找FooAttribute,它将按预期工作:

[AwesomeFoo]
static class Program
{
    static void Main()
    {
        var foo = (FooAttribute)Attribute.GetCustomAttribute(
            typeof(Program), typeof(FooAttribute));
        if (foo != null)
        {
            int[] nums = foo.Nums; // 1,2,3
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你也许可以把它嵌入里面A,所以你装饰着:

[A.FooMonths]
Run Code Online (Sandbox Code Playgroud)

或类似的


Jon*_*Jon 9

不幸的是,这是不可能的.编译器将属性(包括其参数的值)放入程序集元数据中,因此它必须能够在编译时对它们进行求值(因此对常量表达式的限制;数组创建表达式的例外显然是因为否则你根本就没有数组参数.

相反,实际初始化的代码A.Months仅在运行时执行.


Ahm*_*IEM 5

简短的回答:没有。

但是你可以通过key来引用int数组:

public class A
{
    public static readonly Dictionary<int, int[]> NumsArrays 
              = new[]{{1, new[]{1,1,1}}, {2, new[]{2,2,2}}, {3, new[]{3,3,3}}};
    public const int Num1 = 1;
    public const int Num2 = 2;
    public const int Num3 = 3;
}

public class FooAttribute : Attribute
{
    public int NumsId { get; set; }

    FooAttribute()
    {
    }
}

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

//Evaluation:
int id = (FooAttribute) Attribute.GetCustomAttribute(type, typeof (FooAttribute));
int[] result = A.NumsArrays[id];//result is {3,3,3}
Run Code Online (Sandbox Code Playgroud)