如何将列表传递给construtor?
它显示一条消息:
错误14属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式
public class CustomAuthorize : AuthorizeAttribute {
private List<string> multipleProgramID;
//constructor
public CustomAuthorize(List<string> _multipleProgramID) {
multipleProgramID = _multipleProgramID;
}
}
[CustomAuthorize(new List<string>(new string[] { ProgramList.SURVEY_INPUT, ProgramList.SURVEY_OUTPUT } ))]
[HttpPost]
public ActionResult DeleteWaterQualityItems(string sourceID, string wqID) {
// ..other code...
}
public class ProgramList {
public const string SURVEY_INPUT = "A001";
public const string SURVEY_INPUT = "A002";
}
答案 0 :(得分:12)
问题不在于将List<string>
传递给一般的构造函数 - 问题在于您尝试将其用于属性。你基本上不能这样做,因为它不是编译时常量。
看起来ProgramList
实际上是一个枚举 - 所以你可能想把它变成一个枚举:
[Flags]
public enum ProgramLists
{
SurveyInput,
SurveyOutput,
...
}
然后让你的CustomAuthorizeAttribute
(应该这样命名,后缀为Attribute
)在构造函数中接受ProgramLists
。您将其指定为:
[CustomAuthorize(ProgramLists.SurveyInput | ProgramLists.SurveyOutput)]
然后,您可以使用单独的方法将每个ProgramLists
元素映射到字符串,例如"A001"
。这可以通过将属性应用于每个元素,或者在某处具有Dictionary<ProgramLists, string>
来完成。
如果确实希望继续使用这样的字符串,您可以让CustomAuthorizeAttribute
接受一个以逗号分隔的列表,或者将其设为数组而不是列表并使用参数阵列:
[AttributeUsage(AttributeTargets.Method)]
public class FooAttribute : Attribute
{
public FooAttribute(params string[] values)
{
...
}
}
[Foo("a", "b")]
static void SomeMethod()
{
}
答案 1 :(得分:5)
您无法使用List&lt; T&gt;。
属性对参数和属性类型有限制,因为它们必须在编译时可用。 Using attributes in C#
改为使用数组:
//constructor
public CustomAuthorize(string[] _multipleProgramID)
{
...
}
// usage
[CustomAuthorize(new string[] { ProgramList.SURVEY_INPUT, ProgramList.SURVEY_OUTPUT })]
答案 2 :(得分:1)
我尝试做类似的事情,最后在属性构造函数中使用逗号分隔string
并使用string.Spilt(',')
将其转换为数组。
答案 3 :(得分:1)
您只需在自定义属性构造函数中使用“params”关键字,并使您的programList“枚举”
[CustomAttribute(ProgramList.SURVEY_INPUT, ProgramList.SURVEY_OUTPUT)]
[HttpPost]
public ActionResult DeleteWaterQualityItems(string sourceID, string wqID) {
// ..other code...
}
自定义属性类中的使用此
public class CustomAuthorize : AuthorizeAttribute {
//Constructor
public CustomAuthorize (params ProgramList[] programListTypes) {
multipleProgramID= programListTypes;
}
private ProgramList[] multipleProgramID;
}
并且你枚举了课程
public enum ProgramList : int
{
SURVEY_INPUT = 001;
SURVEY_OUTPUT =002;
}
答案 4 :(得分:0)
一种可能的选择:
public class ConstraintExpectedValues : ConstraintAttribute
{
public ConstraintExpectedValues(object[] expectedValues)
{
this.ExpectedValues = expectedValues;
}
public object[] ExpectedValues { get; set; }
}
用法:
[ConstraintExpectedValues(new object[] {5,7,9})]