使用泛型委托或其他方式减少代码
本文关键字:其他 方式减 代码 泛型 | 更新日期: 2023-09-27 18:32:45
你好,你能帮我减少 C# 中的代码吗,我有很多这样的函数我想减少一个带有参数函数的函数的代码,稍后我将发送。
public void WriteTransportCurrectCategoryTypes()
{
var jStr = GetJSONString("GetBusTypes");
var jArr = JArray.Parse(jStr);
var tTypes = new List<TransportCurrentCategoryType>();
foreach (dynamic d in jArr)
{
var tType = new TransportCurrentCategoryType();
ParseTransportCurrentCategoryType(tType, d);
tTypes.Add(tType);
}
}
public void WriteBusModelSpecs()
{
var jStr = GetJSONString("GetBusModelSpecs");
var jArr = JArray.Parse(jStr);
var specs = new List<Characteristic>();
foreach (dynamic d in jArr)
{
var spec = new Characteristic();
ParseBusModelSpecs(spec, d);
specs.Add(spec);
}
}
我尝试将委托与通用一起使用,但它不起作用
public delegate void ParseParameters<T>(T objectClass,dynamic a);
private static void ParceBusClass(BusClass busClass,dynamic a)
{
busClass.Name = a.Name;
busClass.Transport = new TransportCategory {Id = a.BusModelCategoryId};
}
那我叫它:
GetCollectionFromJSON<BusClass>("", ParceBusClass);
private static List<T> GetCollectionFromJSON<T>(string functionName, ParseParameters<T> parseFunk){
/****/
parseFunk<T>(busClass, a);
/***/
}
它需要错误,
通常,您可以使用以下内容:
public List<T> Write<T>(string name, Func<T> factory, Action<T, dynamic> parser)
{
var jStr = GetJSONString(name);
var jArr = JArray.Parse(jStr);
var result = new List<T>();
foreach (dynamic d in jArr)
{
var item = factory();
parser(item, d);
result.Add(item);
}
return result;
}
你可以这样称呼它:
Write<Characteristic>(
"GetBusModelSpecs", () => new Characteristic(), ParseBusModelSpecs);
Write<TransportCurrentCategoryType>(
"GetBusTypes", () => new TransportCurrentCategoryType(),
ParseTransportCurrentCategoryType);
如果大多数或所有类都有默认构造函数,则可以通过提供重载来缩短此构造函数:
public List<T> Write<T>(string name, Action<T, dynamic> parser)
where T : new()
{
return Write<T>(name, () => new T(), parser);
}
现在你可以这样称呼它:
Write<Characteristic>("GetBusModelSpecs", ParseBusModelSpecs);
Write<TransportCurrentCategoryType>(
"GetBusTypes" ,ParseTransportCurrentCategoryType);
此答案没有考虑到可能存在使用JSON库的更好方法。有关示例,请参阅I4V的评论。
使用工厂方法创建通用抽象父类Writer
用于解析 json:
public abstract class Writer<T>
{
private readonly string _url;
public Writer(string url)
{
_url = url;
}
public void Write()
{
var jStr = GetJSONString(_url);
var jArr = JArray.Parse(jStr);
var tTypes = new List<T>();
foreach (dynamic d in jArr)
tTypes.Add(Parse(d));
// other logic here
}
protected abstract T Parse(object d); // implemented by concrete writers
private string GetJSONString(string url)
{
// getting json string here
}
}
然后为要处理的每种类型创建 concreate 子类(它们应指定用于加载 JSON 的 url 并覆盖抽象 Parse 方法):
public class TransportCurrectCategoryWriter : Writer<TransportCurrectCategory>
{
public TransportCurrectCategoryWriter()
: base("GetBusTypes")
{
}
protected override TransportCurrectCategory Parse(object d)
{
// parse TransportCurrectCategory and return parsed instance
}
}
用法:
var writer = new TransportCurrectCategoryWriter();
writer.Write();
没有重复的代码。易于阅读和理解。