簡體   English   中英

如何在C#中檢查參數是否與枚舉中的值匹配?

[英]How can I check a parameter matches a value in my enum in C#?

我有這個枚舉:

public enum ContentKey {
    Menu = 0,
    Article = 1,
    FavoritesList = 2
};

這個動作方法:

public ActionResult Edit(string pk, string rk, int row = 0) {
    try {
        var content = _contentService.Get(pk, rk);

以下類Content基於TableServiceEntity 請注意, TableServiceEntity是我所有數據類所共有的。

public class Content : TableServiceEntity 
{

public abstract class TableServiceEntity
{
    protected TableServiceEntity();
    protected TableServiceEntity(string partitionKey, string rowKey);
    public virtual string PartitionKey { get; set; }

有沒有一種方法可以檢查pk值是否與枚舉值之一匹配? 我不確定該如何檢查。 我假設我需要在Content類中進行檢查,但是我不確定如何覆蓋virtual string並在沒有匹配項時引發異常。

更新 :如果可能的話,我想在Content類的get集合中執行此操作,但是我不確定如何向此類添加get集合。

您可以使用Enum.IsDefined來查看string與Enum值匹配:

public enum ContentKey
{
    Menu = 0,
    Article = 1,
    FavoritesList = 2
}

static bool Check(string pk)
{
    return Enum.IsDefined(typeof(ContentKey), pk);
}

static void Main(string[] args)
{
    Console.WriteLine(Check("Menu"));
    Console.WriteLine(Check("Foo"));
}

您還可以定義一個setter,除非新value被定義為枚舉,否則它不會設置背景字段:

class Foo
{
    private string pk;

    public string PK
    {
        get
        {
            return this.pk;
        }
        set
        {
            if(Enum.IsDefined(typeof(ContentKey), value))
            {
                this.pk = value;
            }
            else
            {
                throw new ArgumentOutOfRangeException();
            }
        }
    }
}

這是一個非自動屬性,您可以在其中自行定義后備字段。 可通過value關鍵字訪問新值。

您可以使用Enum.Parse()

ContentKey key = (ContentKey) Enum.Parse(typeof(ContentKey), pk);

如果pkContentKey定義的任何命名常量都不匹配,它將拋出ArgumentException

嘗試這個。

if(Enum.IsDefined(typeof(ContentKey),pk))
{
   //Do your work;
}

暫無
暫無

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

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