奇怪的属性错误

res*_*sgh 3 c# attributes compiler-errors

我有这个解决方案愉快地工作,我添加了这个属性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public class metadata : Attribute
{
    string mid;
    string mdescription;
    Dictionary<string, string> mdata;
    public string id
    {
        get
        {
            return mid;
        }
    }
    public string description
    {
        get
        {
            return mdescription;
        }
    }
    public Dictionary<string, string> data
    {
        get
        {
            return mdata;
        }
    }
    public metadata(string thisid, string thisdescription, params KeyValuePair<string, string>[] thisdataarray)
    {
        mid = thisid;
        mdescription = thisdescription;
        mdata = new Dictionary<string, string>();
        if (thisdataarray != null)
        {
            foreach (KeyValuePair<string, string> thisvaluepair in thisdataarray)
            {
                mdata.Add(thisvaluepair.Key, thisvaluepair.Value);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我添加了一些这个属性的声明,所有[metadata(null,null)]都没有错误.不知何故,当我编译时,对于每个[metadata(null,null)],"错误CS0182:属性参数必须是常量表达式,属性参数类型的typeof表达式或数组创建表达式",但是没有行或列或文件,只有项目.什么地方出了错?谢谢.

小智 6

问题是KeyValuePair不支持作为属性参数类型.根据C#语言规范:

属性类的位置和命名参数的类型仅限于属性参数类型,它们是:

  • 以下类型之一:bool,byte,char,double,float,int,long,sbyte,short,string,uint,ulong,ushort.
  • 类型对象.
  • 类型System.Type.
  • 枚举类型,前提是它具有公共可访问性,并且嵌套类型(如果有)也具有公共可访问性.
  • 上述类型的一维阵列.

作为一种解决方法,您可以传递一个字符串数组,其中奇数成员是键,甚至成员都是值.然后在属性构造函数中,您可以创建Dictionary.