在 C# 中调用扩展方法的不同方法

Different ways to call an extension method in c#

您好,我有一个简单的枚举服务,其中定义的扩展方法很少

public enum Service
{
   //enum values ..
}

public static class ServiceExtensions
{
   internal static string GetSomeCode(this Service service)
   {
      // Does something
   }

   //another extension method that calls GetSomeCode()
   internal static string GetSomeOtherData(this Service service)
   {
      // Look at the call for extension method here
      string code = GetSomeCode(service);
   }
}

我知道调用扩展方法的语法类似于调用 this 指定类型的成员函数。

在上面的例子中应该是-

string code = service.GetSomeCode();

我在项目的其他地方发现了类似的语法用法。我的问题是这两个电话之间有什么区别。如果不是,那么我应该更喜欢使用哪个?

不,没有区别。此外,后者(service.GetSomeCode())在编译过程中会被转换为前者(GetSomeCode(service))。

如果您访问 sharplab.io 并粘贴以下代码:

public enum Service
{
}

public static class ServiceExtensions
{
   internal static string GetSomeCode(this Service service)
   {
       return "";
   }

   internal static string GetSomeOtherData(this Service service)
   {
      
      string code = service.GetSomeCode();
      return code;
   }
}

然后你会看到反编译后的代码是这样的:

using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;

[assembly: Extension]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
public enum Service
{

}
[Extension]
public static class ServiceExtensions
{
    [Extension]
    internal static string GetSomeCode(Service service)
    {
        return "";
    }

    [Extension]
    internal static string GetSomeOtherData(Service service)
    {
        return GetSomeCode(service);
    }
}

所以,它只是一个语法糖。