【发布时间】: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#