簡體   English   中英

通過屬性c#解析字符串值

[英]Parse string value via attribute c#

我正在使用ASP.NET MVC並且具有以下模型類:

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

但這並不符合我的要求。 當我不在所請求的URL傳遞list參數時,我的列表是black 但我希望,如果list參數不是blackwhite字符串,則list必須為null。 是否可以編寫自定義屬性[IsParsable]並將其添加到列表屬性。

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

簡單的辦法:

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

虛擬對象必須是第一個(映射到0 == default(Enum)

傳遞黑色或白色的值的唯一方法是傳遞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 )。 使用可為空的類型會使您更難忘記這一點,但是會使您的代碼有些混亂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM