简体   繁体   English

为什么Enum上的HasFlag扩展方法胜过Enum.HasFlag?

[英]Why does HasFlag extension method on Enum trump Enum.HasFlag?

If I create an extension method on Enum called HasFlag , whenever I try to call HasFlag on an enum instance, it uses the extension method, rather than the instance method. 如果我在Enum上创建一个名为HasFlag的扩展方法,每当我尝试在枚举实例上调用HasFlag时,它都使用扩展方法,而不是实例方法。 Why? 为什么?

public static class Extensions
{
  public static bool HasFlag(this Enum e)
  {
    return false
  }
}

With code: 使用代码:

public enum Foo
{
  A, B, C
}

public void Whatever()
{
  Foo e = Foo.A;
  if (e.HasFlag())
  {
    // ...
  }
}

Compiles to: 编译为:

public void Whatever()
{
  Foo e = Foo.A;
  if (Extensions.HasFlag(e))
  {
    // ...
  }
}

Why doesn't the compiler use the Enum.HasFlag instance method? 为什么编译器不使用Enum.HasFlag实例方法?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. 扩展方法使您可以向现有类型“添加”方法,而无需创建新的派生类型,重新编译或以其他方式修改原始类型。 Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. 扩展方法是一种特殊的静态方法,但它们被称为扩展类型的实例方法。 For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. 对于用C#和Visual Basic编写的客户端代码,调用扩展方法和实际在类型中定义的方法之间没有明显区别。

Extension methods cannot be override on instance main methods and it will not know which method to call: 扩展方法不能覆盖实例主方法,它不知道调用哪个方法:

The call is ambiguous between the following methods 以下方法之间的调用不明确

The only way around this is to call your extension method using normal static method syntax. 解决此问题的唯一方法是使用常规静态方法语法调用扩展方法。 So instead of this: 所以不是这样的:

e.HasFlag();

you would have to do this: 你必须这样做:

Extensions.HasFlag(e);

But if you add other parameters to your extension methods then it is not same to main methods, so when you call HasFlag method, the extension method called actually. 但是如果你在扩展方法中添加其他参数,那么它与main方法不同,所以当你调用HasFlag方法时,实际调用了扩展方法。 For example: 例如:

public static bool HasFlag(this Enum e, bool isNullable)
{
    return false;
}

References: 参考文献:

Extension Methods (C# Programming Guide) 扩展方法(C#编程指南)

Extension Methods, Nulls, Namespaces and Precedence in C# C#中的扩展方法,空值,命名空间和优先级

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM