簡體   English   中英

如何為 C# 中的枚舉名稱和枚舉值取別名? 預期用途是提高代碼可讀性

[英]How to alias enum name and enum values in C#? Intended use is improving code readability

語境

我將花費相當長的時間與 C# API 一起工作。 使用此 API 將意味着非常頻繁地使用來自該 API 的一小組enum (數百范圍內的值的數量)。 這些enum在代碼中隨處可見。

我不喜歡這些enum的命名,因為我發現它們給編寫的代碼增加了很多噪音。 它們使用以下模板命名:

SoftwareNameNameOfTheKindOfEnum.SoftwareNameNameOfTheKindOfEnumKindOfValue

稍作修改但非常相似的示例是:

YZBuiltInCategoryKinds.YZBuiltInCategoryKindsOtherCategory

一個枚舉值很容易占用 50 到 60 個字符,我發現在代碼中使用它們時很難閱讀。

我寧願讀一些東西:

NameOfTheKindOfEnum.KindOfValue

對於上面的示例,這將給出:

CategoryKind.OtherCategory

問題:如何在C#中給enum取別名,不僅給enum類型名取別名,還給enum值取別名。 using指令為類型名稱起別名很容易,但它不會影響enum值名稱。

編輯由於@MarcGravell評論,將static readonly替換為const

我找到的一個解決方案是創建一組存儲在static class 中的const變量,每個enum一個,例如:

public static class CategoryKind
{
    public const YZBuiltInCategoryKinds OtherCategory = YZBuiltInCategoryKinds.YZBuiltInCategoryKindsOtherCategory,
    // etc... add as many readonly variables as there is values for this `enum`
}

使用這些 static 類,代碼如下:

var myProperty = new Property(YZBuiltInPropertyTypes.YZBuiltInPropertyTypesInteger, 10, YZBuiltInCategoryKinds.YZBuiltInCategoryKindsOtherCategory);

會成為

var myProperty = new Property(PropertyType.Int, 10, CategoryKind.OtherCategory);

暫無
暫無

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

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