【发布时间】:2017-01-20 13:29:34
【问题描述】:
我有几个类,我需要解析 json 对象。我看到这个 json 对象的初始循环在所有类中都几乎相同,除了子方法。
例如在Class1.cs中
private static void FindObject(JToken token)
{
switch (token.Type)
{
case JTokenType.Array:
JArray array = token as JArray;
array.ForEach(a => FindObject(a));
break;
case JTokenType.String:
token.Replace(GetNewImgTag(token.ToString()));
break;
case JTokenType.Object:
token.Children().ForEach(t => FindObject(t));
break;
case JTokenType.Property:
JProperty prop = token as JProperty;
if (prop.Value.Type == JTokenType.Array)
{
FindObject(prop.Value);
return;
}
prop.Value = GetNewImgTag(prop.Value.ToString());
break;
default:
throw new NotImplementedException(token.Type + " is not defined");
}
}
private static JToken GetNewImgTag(string text)
{
...
}
和 Class 2.cs 是
private static void FindObject(JToken token)
{
switch (token.Type)
{
case JTokenType.Array:
JArray array = token as JArray;
array.ForEach(a => FindObject(a));
break;
case JTokenType.String:
token.Replace(ReplaceLinks(token.ToString()));
break;
case JTokenType.Object:
token.Children().ForEach(t => FindObject(t));
break;
case JTokenType.Property:
JProperty prop = token as JProperty;
if (prop.Value.Type == JTokenType.Array)
{
FindObject(prop.Value);
return;
}
prop.Value = ReplaceLinks(prop.Value.ToString());
break;
default:
throw new NotImplementedException(token.Type + " is not defined");
}
}
private static JToken ReplaceLinks(string text)
{
...
}
如果你比较这两个类,FindObject() 几乎相同,除了子方法调用。我需要在几个班级中实现这一点。我正在尝试避免这种多重重复方法的创建。
谁能提出更好的设计方法?
我在这里看到了类似的帖子,但我无法将此代表应用于我的场景。
【问题讨论】:
-
为什么不能申请委托。该方法将更改为
FindObject(JToken token, Func<string,JToken> getValue)并应用prop.Value = getValue(prop.Value.ToString()); -
对于
case JTokenType.Property:,为什么不检查该值是否为字符串?它可以是整数或嵌套对象或日期等。
标签: c# generics design-patterns delegates json.net