mercredi 29 avril 2020

In C#, is there any way to reduce these 1 List and two Dictionaries to a single collection, possibly using reflection?

Currently I have the following code:

    using AddFunction = Func<MyDictionary, object, MyDictionary>;

    class MyDictionary {
        public const string AFile = "A.xml";
        public const string BFile = "B.xml";
        public const string CFile = "C.xml";
        public const string DFile = "D.xml";

        private static readonly List<string> fileList = new List<string> { AFile, BFile, CFile, DFile };

        public static readonly Dictionary<string, Type> documentTypeByFileName = new Dictionary<string, Type> {
            {AFile, typeof(ADocument)},
            {BFile, typeof(BDocument)},
            {CFile, typeof(CDocument)},
            {DFile, typeof(DDocument)},
        };

        private static readonly Dictionary<string, AddFunction> functionByFileName = new Dictionary<string, AddFunction> {
                {AFile, (@this, obj) => @this.AddA((A)obj)},
                {BFile, (@this, obj) => @this.AddB((B)obj)},
                {CFile, (@this, obj) => @this.AddC((C)obj)},
                {DFile, (@this, obj) => @this.AddD((D)obj)}
        };
    }

As you can see, it contains 3 different collections.

We need fileList to maintain the order.

We need documentTypeByFileName to get the type of the C# object which the contents of the files will be mapped to. Each of these is just a wrapper for a list of a type which can be predicted by the name (e.g., ADocument's contents will be just a List). So, each of these Document types implements:

    interface DataListable {
        List<object> GetList();
    }

We need functionByFileName to handle each item from each of these lists.

But, as you can see there is a lot of repeating information here.

Is there a way I can reduce this to a single collection and then be able to manipulate the contents of the collection to avoid all this repetition?

I was thinking about possibily using an OrderedDictionary just to remove the List, but it seems that OrderedDictionary would not take parameterized types...





Aucun commentaire:

Enregistrer un commentaire