Enum上的扩展方法 - 无法在Enum本身上公开方法

cll*_*pse 1 c# extension-methods enums

考虑这个枚举:

enum State
{
    On,
    Off
}
Run Code Online (Sandbox Code Playgroud)

...而这个扩展方法:

public static void Foo(this Enum e)
{
    // Here be dragons...
}
Run Code Online (Sandbox Code Playgroud)

如果我想调用Foo(),我必须在Enum的一个属性上State.On.Foo()调用它:...我不能在Enum本身上调用它:State.Foo().

为什么是这样?我需要做什么才能在Enum上调用Foo()

Jon*_*eet 7

如果你试图打电话State.Foo(),那就试着打电话给静态方法Foo.扩展方法扩展了类型的实例.它们就像向该类型添加实例方法,但无法添加任何状态.

举一个为什么这不起作用的例子,你期望这段代码做什么?

int count = IEnumerable<string>.Count();
Run Code Online (Sandbox Code Playgroud)

你不能假冒为类型添加静态方法.这不是扩展方法支持的东西.