![](/img/trans.png)
[英]C# - how do I check if a byte value matches against any flags in a specified flags enum?
[英]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);
如果pk
與ContentKey
定義的任何命名常量都不匹配,它將拋出ArgumentException 。
嘗試這個。
if(Enum.IsDefined(typeof(ContentKey),pk))
{
//Do your work;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.