简体   繁体   中英

Generics in a dictionary used for mapping

I am trying to do something, that might be completely a** backwards. I don't know if I have confused myself, and just need a kick in the right direction or I need to completely rethink everything.

I am working on a simple mapper. The mapper maps from one object property to another object property.

First take was just a simple Dictionary that would map one property name to another. But for the next version I need to do some conversion as well. So I am thinking I will expand the map a little.

Dictionary where MyMap is a class that has two properties on it. A string which corresponds to the string above, and a Func which is the conversion Func. My code will then look for the Func and if present use it to convert the value before applying it on the object mapped to.

My problem is that I would like to have the Func take a bool as input if it is a boolean property, a string if it is a string property etc. For example something like this:

dictionary.Add("Open", new MyMap {Name = "Closed", Map = Func<bool, bool> {x => !x}};
dictionary.Add("AmountUsd", new MyMap {Name = "AmountEur", Map = Func<decimal, decimal> {x => x * conversionRate}};

I can't do that with generics as far as I can gather. The Funcs cannot have different signatures.

I could of course just have a Func and then cast the value inside the Func, but that isn't as nice.

Have a I confused myself completely, or is there another approach that I use?

Thanks

You need to make the class generic, then make a dictionary that contains a non-generic base type:

interface IMyMap {
    ...
}
class MyMap<T> : IMyMap {
    public Func<T, T> Map { get; set; }
}

var dict = new Dictionary<string, IMyMap> {
    { "Open", new MyMap<bool> { ... }
};

Obviously, you will not be able to interact with the type parameter from the dictionary, since you don't know what type it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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