c# - 是否在扩展方法类中调用扩展方法?

标签 c# extension-methods

<分区>

在扩展方法内部,有时使用其他扩展方法是有意义的。我拿不定主意你是否应该使用“this”语法。

public static class StringExtensions
{
    // Foo vs Foo1
    public static string Foo(this string s)
    {
        return s + "Foo" + s.Bar(); // "this" syntax
    }

    public static string Foo1(this string s)
    {
        return s + "Foo" + Bar(s);
    }

    public static string Bar(this string s)
    {
        return s + "Bar";
    }
}

FooFoo1。出现两个问题:

  1. 表现。生成的 IL 代码有什么不同吗?
  2. 代码设计。这两种方法中哪一种更可取?为什么?

最佳答案

  1. 没有性能差异,因为扩展方法被编译为常规静态方法调用。

  2. 我会说 this 语法更可取,因为如果您将方法声明为扩展方法 (this string s) - 这对 始终将其作为扩展方法调用,不要与常规静态调用混淆。

关于c# - 是否在扩展方法类中调用扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44003832/

相关文章:

c# - 发送 HTML 参数和文件路径参数?

c# - 使用 IdentityServer4 添加自定义 API 访问声明

c# - 如何在 C# 中使用 DLL 函数而不添加 DLL 作为引用?

c# - 构造函数中有很多参数的最佳实践?

asp.net-mvc - 未找到 Html 帮助程序扩展

.net - 扩展方法的使用

c# - 网络摄像头时间不准确,设置曝光时间

c# - LINQ 依赖计算赋值

.net - 枚举扩展方法

c# - 根据拼写距离按属性区分