如何删除仅在类型上有所不同但使用非默认构造函数的方法之间的重复?

Mor*_*aos 3 .net c# methods optimization

您好我有很多方法(下面两个例子)看起来几乎完全相同.所不同的是JSON breanch的名字被处理,返回列表的类型添加到列表的对象类型.我知道这些示例方法在它的主体中需要一些优化,但是案例是传递返回值的类型和当前需要的方法的类型,并使它全部工作.如果有可能我想避免代替调用方法.

方法1

    public static List<Box> JsonToListOfBoxes(string data)
    {
        List<Box> ListOfBoxes = new List<Box>();
        if(!string.IsNullOrEmpty(data))
        {
            JObject productsJson = JObject.Parse(data);
            JToken jtkProduct;

            jtkProduct = productsJson["boxes"];

            if(jtkProduct != null)
                if(jtkProduct.HasValues)
                {
                    int childrenCount = productsJson["boxes"].Count();
                    for(int x = 0;x < childrenCount;x++)
                        ListOfBoxes.Add(new Box(productsJson["boxes"][x]));
                }
        }

        return ListOfBoxes;
    }
Run Code Online (Sandbox Code Playgroud)

方法2

    public static List<Envelope> JsonToListOfEnvelopes(string data)
    {
        List<Envelope> ListOfEnvelopes = new List<Envelope>();
        if(!string.IsNullOrEmpty(data))
        {
            JObject productsJson = JObject.Parse(data);
            JToken jtkProduct;

            jtkProduct = productsJson["envelopes"];

            if(jtkProduct != null)
                if(jtkProduct.HasValues)
                {
                    int childrenCount = productsJson["envelopes"].Count();
                    for(int x = 0;x < childrenCount;x++)
                        ListOfEnvelopes.Add(new Envelope(productsJson["envelopes"][x]));
                }
        }

        return ListOfEnvelopes;
    }
Run Code Online (Sandbox Code Playgroud)

小智 5

使用泛型,您可以更改如下:(没有参数化的通用构造函数)

    public static List<T> JsonToListOfEnvelopes<T>(string data, string searchString, Func<string, T> creator)
    {
        List<T> ListOfEnvelopes = new List<T>();
        if (!string.IsNullOrEmpty(data))
        {
            JObject productsJson = JObject.Parse(data);
            JToken jtkProduct;

            jtkProduct = productsJson[searchString];

            if (jtkProduct != null)
                if (jtkProduct.HasValues)
                {
                    int childrenCount = productsJson[searchString].Count();
                    for (int x = 0; x < childrenCount; x++)
                        ListOfEnvelopes.Add(creator(productsJson[searchString][x]));
                }
        }

        return ListOfEnvelopes;
    }
Run Code Online (Sandbox Code Playgroud)

你可以称之为

        var result = JsonToListOfEnvelopes("data", "boxes", c => { return new Box(c); });
        var result = JsonToListOfEnvelopes("data", "envelopes", c => { return new Envelope(c); });
Run Code Online (Sandbox Code Playgroud)