【问题标题】:Parse string value via attribute c#通过属性 c# 解析字符串值
【发布时间】:2014-05-07 07:12:28
【问题描述】:

我正在使用ASP.NET MVC,并且我有以下模型类:

public enum ListType
{
    black,
    white
}
public class ListAddSiteModel : ApiModel
{
    [RequestParameter]
    public ListType list { get; set; }
}

但它并没有按照我想要的方式工作。当我没有在请求的URL 中传递列表参数时,我的列表是black。但我希望如果列表参数不是blackwhite 字符串,那么list 必须为空。是否可以编写自定义属性[IsParsable] 并将其添加到列表属性中。

public class ListAddSiteModel : ApiModel
{
    [RequestParameter]
    [IsParsable]
    public ListType list { get; set; }
}

【问题讨论】:

  • list 不能为空,因为enum 不是可空类型。您应该将其定义为 public ListType? list 或者给 ListType 一个默认值 (ListType.none) - 您还应该将这些枚举和属性名称大写
  • @RGraham 问号是什么意思?

标签: c# asp.net-mvc custom-attributes


【解决方案1】:

简单的出路:

public enum ListType
{
    novalue = 0, 
    black,
    white
}

假人必须是第一个(映射到0 == default(Enum)

【讨论】:

  • 仍然不会阻止某人传递无效值,如果那是实际问题
【解决方案2】:

您可以传递黑色或白色值的唯一方法是传递int。您可以通过在调用 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;
    }
}

您还可以将此与 Henk Holterman 的答案结合起来,并在您的枚举中添加一个等于 0 的 NA 成员。这可能会使您的代码更易于阅读。

在这两种情况下,您的代码都必须处理特殊值(NAnull)。使用可为空的类型会让人更难忘记这一点,但确实会有点乱码。

【讨论】:

  • ListType? _listType; 中的问号是什么意思。这个结构是不可搜索的。
  • 这是 nullable type 的 C# 语法。它用于允许处理否则不允许空值的值类型的空值。从 .NET 2.0 开始它就在 C# 中,所以它几乎无处不在。
  • 这里需要明确的属性声明吗?如果在类型中找不到提供的值,MVC 是否会自动将可为空的枚举绑定到 null
  • @RGraham 这不会阻止用户代码传递错误的值。如果这不是问题,您可以保留可为空的声明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2012-03-21
  • 2012-03-29
  • 1970-01-01
  • 2013-02-03
  • 2014-08-18
  • 2021-10-28
相关资源
最近更新 更多