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

时间:2017-05-16 14:09:12

标签: 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";
    }
}

Foo vs Foo1。出现了两个问题:

  1. 性能。生成的IL代码是否存在差异?
  2. 代码设计。两种方法中哪一种更可取?为什么?

1 个答案:

答案 0 :(得分:3)

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

  2. 我认为this语法是首选的,因为如果您将方法声明为扩展方法(this string s) - 始终调用它是件好事作为扩展方法,不要与常规静态调用混淆。

相关问题