我正在寻找在属性中建立字典的方法。
我知道在C#属性中使用AllowMultiple
,但这会导致该属性被调用并(在我的情况下,因为它是一个过滤器)被触发了两次。
基本上,我想要这种行为:
[MyAttribute("someKey", "value1", "value2", "value3")]
[MyAttribute("someOtherKey", "value1", "value2", "value3")]
[在Dictionary<string, HashSet<string>>
内部产生MyAttribute
。但是,由于明显的原因,这在每行实例化一个全新的MyAttribute
时不起作用。
是否有解决此问题的好方法?属性是否完全支持此功能,还是我需要提出一些轻松的方法将参数传递到一个属性声明中?
编辑:我应该注意...这是用于授权过滤器的。它应该为多个可能的值授权多个环境(键)。但是,我不能使用该属性的多个实例,因为这样会多次触发过滤器。
我正在寻找在属性中建立字典的方法。我知道在C#属性中使用AllowMultiple,但这会导致该属性被调用并(在我的情况下,因为它是一个过滤器)触发了...
[这是将复杂信息插入到属性中的一种方法,使用与System.ComponentModel.TypeConverterAttribute相同的模式:将复杂性隐藏在Type内,并使用typeof(MyType)作为赋予该属性的编译时间常数。 >
public class MyAttributeAttribute : AuthorizeAttribute
{
public MyAttributeAttribute(Type t) : base()
{
if (!typeof(MyAbstractDictionary).IsAssignableFrom(t))
{
// ruh roh; wrong type, so bail
return;
}
// could also confirm parameterless constructor exists before using Activator.CreateInstance(Type)
Dictionary<string, HashSet<string>> dictionary = ((MyAbstractDictionary)Activator.CreateInstance(t)).GetDictionary();
this.Roles = "Fill Roles by using values from dictionary";
// fill any other properties from the dictionary
}
}
public abstract class MyAbstractDictionary
{
public abstract Dictionary<string, HashSet<string>> GetDictionary();
}
public class MyDictionary : MyAbstractDictionary
{
public MyDictionary() { } // gotta have a parameterless constructor; add it here in case we actually make another constructor
public override Dictionary<string, HashSet<string>> GetDictionary()
{
Dictionary<string, HashSet<string>> dict = new Dictionary<string, HashSet<string>>();
// build dictionary however you like
return dict;
}
}