【问题标题】:c# Prioritizing extension methods (only)c# 优先扩展方法(仅限)
【发布时间】:2016-02-02 23:40:54
【问题描述】:

让我从代码开始...请注意,这不是关于覆盖实例方法的问题 - 这纯粹涉及扩展方法。此代码用于 Unity3D 游戏引擎,版本 5.3.x

public static class ExtentionMethods {

    public static string ToJson<T>(this List<T> list) {
        string s = "[";
        for (int i = 0; i < list.Count; i++) {
            if (i > 0)
                s += ",";
            s += list[i].ToJson();
        }
        return s + "]";
    }

    public static string ToJson(this object o) {
        if (o == null)
            return "null";
        return o.ToString();
    }

    public static string ToJson(this string value){
        return "\"" + value + "\"";
    }
}

public List<string> list = new List<string>();
void Start () {
    list.Add ("dog0");
    list.Add ("dog1");
    list.Add ("dog2");
    Debug.Log (list.ToJson());  

    string s = "elephants";
    Debug.Log (s.ToJson());  
}

输出如下:

[dog0,dog1,dog2]
"elephants"

似乎调用 ToJson() 函数的字符串可以使用对象或字符串类型。有没有办法让它只使用字符串版本的方法?

【问题讨论】:

  • 我想知道现成的 JSON 序列化库是否不是一个更好的主意(除非您已经通过性能分析器的测量确定了代码热点)。 JSON 序列化是一个已解决的问题。
  • 如果他关心性能,他至少会使用字符串生成器。

标签: c#


【解决方案1】:

此时:

s += list[i].ToJson();

...所有编译器都知道list[i] 是一个对象,所以这就是你得到的扩展方法。您必须查看 list[i] 的类型,如果它是字符串,则调用字符串重载,例如,

object o = list[i];
string s = o as string;
if (s != null)
{
    s += s.ToJson();
}
else
{
    s += o.ToJson();
}

扩展方法是很好的语法糖,但不要对泛型魔法期望过高。 :-)

【讨论】:

  • unity3d 标签在这里并不适用;这是一个纯粹的C# 问题,我想。
【解决方案2】:

如果不检查类型并使用强制转换调用匹配类型的 ToJson 方法,就没有办法。 (Petter 已经给出了答案)

如果我遇到类似的问题,我会为字符串列表添加另一个扩展:

public static string ToJson(this List<string> list) {
   // ... Body is the same with other ToJson<T>(List<T>)
}

这样,字符串列表会在编译期间绑定到此方法。由于编译器知道值是字符串,因此内部 ToJson 方法将与字符串一正确绑定。

【讨论】:

    【解决方案3】:

    你必须检查 T 是什么类型:

    s += typeof(T)==typeof(string) ? list[i].ToString().ToJson() : list[i].ToJson();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多