简体   繁体   English

如何在C#中检查参数是否与枚举中的值匹配?

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

I have this enum: 我有这个枚举:

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

This action method: 这个动作方法:

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

The following class Content which is based on the TableServiceEntity . 以下类Content基于TableServiceEntity Note that TableServiceEntity is common to all my data classes. 请注意, TableServiceEntity是我所有数据类所共有的。

public class Content : TableServiceEntity 
{

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

Is there a way I can check the value of pk matches one of the enum values? 有没有一种方法可以检查pk值是否与枚举值之一匹配? What I am not sure about is how I can check this. 我不确定该如何检查。 I assume I need to have the check in the Content class but I am not sure how to override the virtual string and throw an exception when there's no match. 我假设我需要在Content类中进行检查,但是我不确定如何覆盖virtual string并在没有匹配项时引发异常。

Update : If possible I would like to do this in the Content class get set but I am not sure how to add a get set to this class. 更新 :如果可能的话,我想在Content类的get集合中执行此操作,但是我不确定如何向此类添加get集合。

You can use Enum.IsDefined to see if a string matches an Enum value: 您可以使用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"));
}

You can also define a setter that does not set the backing field unless the new value is defined the enum: 您还可以定义一个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();
            }
        }
    }
}

This is a non-automatic property where you define the backing field yourself. 这是一个非自动属性,您可以在其中自行定义后备字段。 The new value is accessible via the value keyword. 可通过value关键字访问新值。

You can use Enum.Parse() : 您可以使用Enum.Parse()

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

It will throw an ArgumentException if pk does not match any named constant defined in ContentKey . 如果pkContentKey定义的任何命名常量都不匹配,它将抛出ArgumentException

Try this. 尝试这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM