我可以使用数组或其他可变数量的参数初始化 C# 属性吗? [英] Can I initialize a C# attribute with an array or other variable number of arguments?

查看:23
本文介绍了我可以使用数组或其他可变数量的参数初始化 C# 属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个可以用可变数量的参数初始化的属性?

Is it possible to create an attribute that can be initialized with a variable number of arguments?

例如:

[MyCustomAttribute(new int[3,4,5])]  // this doesn't work
public MyClass ...

推荐答案

属性将采用数组.虽然如果你控制属性,你也可以使用 params 代替(这对消费者更好,IMO):

Attributes will take an array. Though if you control the attribute, you can also use params instead (which is nicer to consumers, IMO):

class MyCustomAttribute : Attribute {
    public int[] Values { get; set; }

    public MyCustomAttribute(params int[] values) {
       this.Values = values;
    }
}

[MyCustomAttribute(3, 4, 5)]
class MyClass { }

您的数组创建语法恰好关闭:

Your syntax for array creation just happens to be off:

class MyCustomAttribute : Attribute {
    public int[] Values { get; set; }

    public MyCustomAttribute(int[] values) {
        this.Values = values;
    }
}

[MyCustomAttribute(new int[] { 3, 4, 5 })]
class MyClass { }

这篇关于我可以使用数组或其他可变数量的参数初始化 C# 属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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