我有几个类,我需要解析json对象。我看到这个 json 对象的初始循环在除子方法之外的所有类中几乎相同。
例如,在类 1 中.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)
{
...
}
和类 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() 几乎相同。我需要在几个类中实现这一点。我正在尝试避免创建多个重复方法。
谁能提出更好的设计方法?
我在这里看到了类似的帖子,但我无法将此委托应用于我的方案。
避免在多个类似方法中使用重复代码 (C#)
一个简单的方法是识别不同的部分,并将其作为您传递给单独函数的委托。
这是一个工作示例。
public static class MyTokenReaderUtilities
{
public static void ConvertEachProperty(JToken token, Func<string, JToken> convertString)
{
switch (token.Type)
{
case JTokenType.Array:
JArray array = token as JArray;
array.ForEach(a => ConvertEachProperty(a, convertString));
break;
case JTokenType.String:
token.Replace(convertString(token.ToString()));
break;
case JTokenType.Object:
token.Children().ForEach(t => ConvertEachProperty(t, convertString));
break;
case JTokenType.Property:
JProperty prop = token as JProperty;
if (prop.Value.Type == JTokenType.Array)
{
ConvertEachProperty(prop.Value, convertString);
return;
}
prop.Value = convertString(prop.Value.ToString());
break;
default:
throw new NotImplementedException(token.Type + " is not defined");
}
}
}
现在,在类 1 中:
private static void FindObject(JToken token)
{
MyTokenReaderUtilities.ConvertEachProperty(token, GetNewImgTag);
}
在第 2 类中:
private static void FindObject(JToken token)
{
MyTokenReaderUtilities.ConvertEachProperty(token, ReplaceLinks);
}