在C#属性中构建字典
我想在属性中建立一个字典 我知道如何在C#attributes中使用在C#属性中构建字典,c#,attributes,C#,Attributes,我想在属性中建立一个字典 我知道如何在C#attributes中使用AllowMultiple,但这会导致调用该属性并(在我的例子中,因为它是一个过滤器)触发两次 本质上,我想要这种行为: [MyAttribute(“someKey”、“value1”、“value2”、“value3”)] [MyAttribute(“someOtherKey”、“value1”、“value2”、“value3”)] 在MyAttribute中生成字典。但是,由于明显的原因,这不起作用,因为每一行都实例化一
AllowMultiple
,但这会导致调用该属性并(在我的例子中,因为它是一个过滤器)触发两次
本质上,我想要这种行为:
[MyAttribute(“someKey”、“value1”、“value2”、“value3”)]
[MyAttribute(“someOtherKey”、“value1”、“value2”、“value3”)]
在MyAttribute
中生成字典
。但是,由于明显的原因,这不起作用,因为每一行都实例化一个全新的MyAttribute
有什么好办法吗?属性是否支持这一点,或者我是否需要想出一些厚颜无耻的方法将参数传递到单个属性声明中
编辑:我应该注意。。。这是用于授权筛选器的。它应该能够为多个潜在值授权多个环境(密钥)。但是,我不能使用属性的多个实例,因为这样会多次触发筛选器。这里有一种方法可以将复杂信息插入属性,使用与System.ComponentModel.TypeConverterAttribute相同的模式:将复杂性隐藏在类型中,并使用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;
}
}
然后,您可以继续使用不同的字典创建类
MyDictionary2
,并将其用作其他事物的属性的typeof()。您现在还可以使用运行时信息(!)来构建字典,而不仅仅是硬编码的值。您能解释一下为什么要使用属性吗?这是用于授权筛选器的。它应该能够为多个潜在值授权多个环境(密钥)。但是,我不能使用属性的多个实例,因为过滤器将被触发多次。为什么过滤器会被触发多次?(只是为了帮助获得正在发生的事情的心智模型。更多上下文总是有帮助的。)您是否在进行反射以查找具有此属性的所有内容,然后在该成员的.GetCustomAttributes()方法上单步执行所有内容?如果是这样的话,你就不能遍历属性的所有实例,构建用AllowMultiple实现的“字典”,然后触发过滤器一次吗?@SeanSkelly过滤器被多次命中,因为过滤器就是这样工作的。每次应用它们时,它都会为请求所经历的过程添加一层过滤逻辑。我的属性正在扩展AuthorizeAttribute
。没有思考。啊,是的,没有你自己的思考;NET代码本身就是这样做的。有一种将复杂代码注入属性的方法,类似于System.ComponentModel.TypeConverterAttributes的工作方式-将类型(从TypeConverter继承)插入该属性的构造函数,它使用该类型获取所需的信息。因此,您需要MyAttribute类所需的MyAbstractDictionary类,定义一个MyDictionary类:MyAbstractDictionary,该类重写返回词典的方法,然后使用typeof(MyDictionary)构造MyAttribute。谢谢,这在功能上解决了我的问题。老实说,关于命名/清洁度,这有点像噩梦,好像我对不同的控制器方法有不同的标准,我需要为每个方法创建新的字典类。此外,它们的名称应该描述它们的函数,但这可能会导致一个非常长的类名。
[MyAttribute(typeof(MyDictionary))]
public class ClassToAttribute { }