我可以扩展一个C#Enum,这样我可以通过多种方式获取其值吗?

0 c# extension-methods enums

我有以下枚举:

public enum ContentKey {
    Menu = 0,
    Article = 1,
    Topic = 2
};
Run Code Online (Sandbox Code Playgroud)

当我使用Enum时,我一直在做以下事情:

((int)ContentKey.Topic).ToString("D2")
Run Code Online (Sandbox Code Playgroud)

有没有办法可以创建Enum的扩展,所以我不需要编写上面的代码?

Che*_*hen 5

您可以使用扩展方法:

public static class Ext
{
    public static string ToFormattedString(this ContentKey key, string format)
    {
        //do staff
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

ContentKey.Topic.ToFormattedString("D2")
Run Code Online (Sandbox Code Playgroud)