Enum 上的扩展方法 - 无法公开 Enum 本身的方法
考虑这个 Enum:
enum State
{
On,
Off
}
...以及这个扩展方法:
public static void Foo(this Enum e)
{
// Here be dragons...
}
如果我想调用 Foo(),我必须在 Enum 的属性之一上调用它:State.On.Foo()
...我无法在 Enum 本身上调用它:State.Foo()
。
这是为什么呢?我需要做什么才能在 Enum 本身上调用 Foo() ?
Consider this Enum:
enum State
{
On,
Off
}
... And this extension method:
public static void Foo(this Enum e)
{
// Here be dragons...
}
If I want to call Foo(), I have to call it on one of the Enum's properties: State.On.Foo()
... I can't call it on the Enum itself: State.Foo()
.
Why is this? And what do I need to do, to be able to call Foo() on the Enum itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您尝试调用
State.Foo()
,那就是尝试调用Foo
上的静态方法。扩展方法扩展类型的实例。它们就像向该类型添加实例方法,但无法添加任何状态。举个例子说明为什么这行不通,您希望这段代码做什么?
您不能伪造向类型添加静态方法。它只是扩展方法不支持的东西。
If you try to call
State.Foo()
, that's trying to call a static method onFoo
. Extension methods extend instances of a type. They're like adding instance methods to that type, but without being able to add any state.To give an example of why this wouldn't work, what would you expect this code to do?
You can't fake adding static methods to a type. It's just not something that extension methods support.
这是因为扩展方法只能在实例上调用,而不能在类上调用。它们只是静态方法的语法糖。
This is because extension methods can only be called on instance, not class. They are just a syntactic sugar for static methods.