I had this solution working happily and i added this attribute:
[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);
}
}
}
}
I added a few declarations of this attribute, all [metadata(null, null)] with no errors. Somehow, when I compile, for each [metadata(null, null)] an “error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type” occurs, however with no line or column or file, only the project. What went wrong? Thanks.
The problem is that KeyValuePair is not supported as attribute parameter type.
According to the C# Language specification:
The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:
long, sbyte, short, string, uint, ulong, ushort.
which it is nested (if any) also have public accessibility.
As a workaround you can pass an array of strings where the odd members are keys and even members are values. Then inside the attribute constructor you can create your Dictionary.