C#动态arry in属性

C#动态arry in属性,c#,attributes,C#,Attributes,嗨,我需要在c中的属性中使用动态数组# 例如: public class MyHtmlAttributesAttribute : System.Attribute { private IDictionary<string, string> Attrib { get; set; } public MyHtmlAttributesAttribute() { Attrib = new Dictionary<string, string>

嗨,我需要在c中的属性中使用动态数组#

例如:

 public class MyHtmlAttributesAttribute : System.Attribute
 {
    private IDictionary<string, string> Attrib { get; set; }
    public MyHtmlAttributesAttribute()
    {
        Attrib = new Dictionary<string, string>();
    }
    public MyHtmlAttributesAttribute(params string[][] values)
        : this()
    {             
        foreach (var item in values)
        {
            if (item.Count() < 1)
                throw new Exception("bad length array");
            this.Attrib.Add(item[0].ToLower(), item[1]);
        }

    }
 }

感谢您的回答

本例中的问题不在于属性,而在于数组初始化<代码>{{“Class”、“ltr”}、{“AutoCompleteType”、“Disabled”}}可以在数组初始值设定项中使用,但不能在新的[]表达式中使用。 使用新表达式:
newstring[]]{newstring[]{“Class”,“ltr”},newstring[]{“AutoCompleteType”,“Disabled”}
但由于使用了
params
,因此可以省略封装的新字符串[]:

 [MyHtmlAttributes(new string[]{"Class", "ltr"}, new string[]{"AutoCompleteType" , "Disabled"})]
以下内容纯粹是一种选择

另一种方法是允许应用属性的多个实例,并在获取它们时将它们合并

要允许多个属性,请执行以下操作:

[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
 public class MyHtmlAttributesAttribute : System.Attribute
应用它们作为

    [MyHtmlAttributes("Class", "ltr")]
    [MyHtmlAttributes("AutoCompleteType", "Disabled")]
    public string Email { get; set; }

当然,必须修改属性的构造函数和实现,以便只允许单个attr值对,但是通过这种方式添加/删除一对应该更容易。通过读取属性上的所有MyHtmlAttributes实例来组合它们应该足够简单。

C#属性值仅限于编译时常量和
typeof
运算符。您可以在C#规范中阅读更详细的内容我可以[MyHtmlAttributes(新字符串[]…],但我现在不能使用字符串[][]!!!!!注意,您将有多个没有共享数据的
MyHtmlAttributes
实例。非常感谢您的回答,但当使用第一种样式代码时:[MyHtmlAttributes(新字符串[]{“Class”,“ltr”},新字符串[]]{“…i get error:属性参数必须是常量表达式、typeof表达式或属性参数类型的数组创建表达式
    [MyHtmlAttributes("Class", "ltr")]
    [MyHtmlAttributes("AutoCompleteType", "Disabled")]
    public string Email { get; set; }