简体   繁体   English

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

[英]How can I remove duplication between methods that differ only on type but use non-default constructors?

Hello I got many methods (below 2 examples) that look almost exactly the same. 您好我有很多方法(下面两个例子)看起来几乎完全相同。 The difference is in name of JSON breanch that is processed, type of returned list and type of objects added to list . 不同之处在于处理的JSON breanch的名称, 返回列表的 类型以及添加到列表的对象类型 I know these example methods yet needs some optimization in its body, but the case is to pass type of returned value and type of class which method currently need and make it all work. 我知道这些示例方法在它的主体中需要一些优化,但是案例是传递返回值的类型和当前需要的方法的类型,并使它全部工作。 If it is possible I would like to avoid casting in place of calling method. 如果有可能我想避免代替呼叫方法。

Method 1 方法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;
    }

Method 2 方法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;
    }

Using generics you can change as follows : (without parameterized generic constructor) 使用泛型,您可以更改如下:(没有参数化的通用构造函数)

    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;
    }

And you can call it as 你可以称之为

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

You could make generic method where dataName should be "boxes" or "envelopes": 您可以创建通用方法,其中dataName应为“boxes”或“envelope”:

public static List<T> JsonToListOfBoxes<T>(string data, string dataName)
{
    List<T> ListOfItems = new List<T>();
    if (!string.IsNullOrEmpty(data))
    {
        JObject productsJson = JObject.Parse(data);
        JToken jtkProduct;

        jtkProduct = productsJson[dataName];

        if (jtkProduct != null)
            if (jtkProduct.HasValues)
            {
                int childrenCount = productsJson[dataName].Count();
                for (int x = 0; x < childrenCount; x++)
                    ListOfItems.Add((T)Activator.CreateInstance(typeof(T), productsJson[dataName][x]));
            }
    }

    return ListOfItems;
}

Use example: 使用示例:

var list1 = JsonToListOfBoxes<Box>("dataString", "boxes");
var list2 = JsonToListOfBoxes<Envelope>("dataString", "envelopes");

I just changed @msmolcic logic a bit. 我刚刚改变了@msmolcic逻辑。

public static List<T> JsonToListOfBoxes<T>(string data)
{
    List<T> ListOfItems = new List<T>();
    string dataName = typeof(T) == typeof(Box) ? "boxes" : "envelopes";

      //if there are many types one can try in below way..
      // if (typeof(T) == typeof(Box))
      //  {
      //      dataName = "Box";
      //  }
      //  else if (typeof(T) == typeof(Envelope))
      //  {
      //      dataName = "envelopes";
      //  }

    if (!string.IsNullOrEmpty(data))
    {
        JObject productsJson = JObject.Parse(data);
        JToken jtkProduct;

        jtkProduct = productsJson[dataName];

        if (jtkProduct != null)
            if (jtkProduct.HasValues)
            {
                int childrenCount = productsJson[dataName].Count();
                for (int x = 0; x < childrenCount; x++)
                    ListOfItems.Add((T)Activator.CreateInstance(typeof(T), productsJson[dataName][x]));
            }
    }

    return ListOfItems;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM