[英]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.