[英]Parse string value via attribute c#
I'm using ASP.NET MVC
and I have the follwoing model class: 我正在使用
ASP.NET MVC
并且具有以下模型类:
public enum ListType
{
black,
white
}
public class ListAddSiteModel : ApiModel
{
[RequestParameter]
public ListType list { get; set; }
}
But it doesn't work the way I want. 但这并不符合我的要求。 When I don't pass list parameter in the requested
URL
I have that list is black
. 当我不在所请求的
URL
传递list参数时,我的列表是black
。 But I want that if the list parameter is not black
or white
string then list
must be null. 但我希望,如果list参数不是
black
或white
字符串,则list
必须为null。 Is it possible to write custom attribute [IsParsable]
and just add it to the list property. 是否可以编写自定义属性
[IsParsable]
并将其添加到列表属性。
public class ListAddSiteModel : ApiModel
{
[RequestParameter]
[IsParsable]
public ListType list { get; set; }
}
Easy way out: 简单的办法:
public enum ListType
{
novalue = 0,
black,
white
}
the dummy must be first (map to 0 == default(Enum)
) 虚拟对象必须是第一个(映射到
0 == default(Enum)
)
The only way you can pass a value that is not black or white, is to pass an int
. 传递非黑色或白色的值的唯一方法是传递
int
。 You can prevent that by adding a check in your setter that calls Enum.IsDefined , eg: 您可以通过在设置器中添加一个调用Enum.IsDefined的支票来防止这种情况 ,例如:
ListType? _listType;
public ListType? List
{
get
{
return _listType;
}
set
{
//Enumb.IsDefined doesn't like nulls
if (value==null || Enum.IsDefined(typeof(ListType),value))
_listType=value;
else
_listType=null;
}
}
You can also combine this with Henk Holterman's answer and add an NA
member equal to 0 in your enumeration. 您还可以将其与Henk Holterman的答案相结合,并在枚举中添加等于0的
NA
成员。 This will probably make your code easier to read. 这可能会使您的代码更易于阅读。
In both cases your code will have to take care of the special values ( NA
or null
). 在这两种情况下,您的代码都必须注意特殊值(
NA
或null
)。 Using a nullable type makes it harder to forget this, but does litter your code a bit. 使用可为空的类型会使您更难忘记这一点,但是会使您的代码有些混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.