我应该如何调用重载的扩展方法?

How should I call an overloaded extension method?

假设我有这个扩展方法:

public static string ToJson(this object value, JsonSerializerSettings settings)
{
    return JsonConvert.SerializeObject(value, settings);
}

和超载:

private static readonly JsonSerializerSettings settings = GetTheSettingsSomeWay();
public static string ToJson(this object value)
{
    return ToJson(value, settings); // (1) static call
    return value.ToJson(settings); // (2) using an extension on "this"
}

我应该将重载调用为静态调用还是扩展?

没关系。基本上是一样的。将调用相同的方法,甚至 IL 也是相同的,因为扩展方法 are a code feature, the result in the compiled code is the same.

我在使用扩展方法时遇到的唯一主要问题是 dynamic 关键字:它不解析扩展方法。在这种情况下,您应该始终使用 static 方法。因为你在这里不这样做,所以没关系。