I'm just having a play around with writing an ORM-type project in C#.
Basically, I have a class structure like this:
IDBOperation --- DBReadOperation
DBOperationPool
Basically, a DBReadOperation maps data from the specified database table to a class in my solution, say for example PersonDetails.
The code to do this was taken from an external source (can't quite remember?), and basically returns a generic collection (Collection).
My DBOperationPool needs to be able to take any number of DBReadOperation's and return results for each of them. The logic for that I have down.. but can't seem to get the code to work?
The mapping class also is built on generics.. so how can I instantiate the mapping class to be along the lines of..
MappingClass<?> mappingInstance = new MappingClass<?>();
Collection<?> returnedCollection = mappingInstance.MapData(argument);
How do I (using generics, or reflection, or anythi开发者_如何学运维ng) figure out what to put where the question marks are in the above? Can it be done? I've had a search around and nothing seems to be related to this exact problem..
Obviously, the easy route is making the pool include the type I want to map towards.. but the whole point of the pool is that I can throw DBReadOperation's at it for, say, PersonDetails, CompanyDetails, etc, and have the data mapped to where it needs to be and return the results properly for each type. With this route, I can throw any number of DBReadOperations into a pool, as long as they deal with a specific type for each DBOperationPool instance.. but thats not what I want..
Does this make sense at all?
Regards,
Simon
Make MappingClass implement some interface, IMappingClass, then refer to that everywhere that you don't know what type the generic will hold.
public interface IMappingClass {
public void DoStuff();
}
public class MappingClass<T> : IMappingClass {
// stuff
}
// ... elsewhere ...
public void DoMappingStuff(IMappingClass map){
map.DoStuff();
// do other stuff...
}
// ...
MappingClass<string> myStringMap = new MappingClass<string>();
DoMappingStuff(myStringMap);
MappingClass<int> myIntMap = new MappingClass<int>();
DoMappingStuff(myIntMap);
Can your DBReadOperation class be generic? Meaning, DBReadOperation<T>
and then you instantiate it with:
var dbReadOperation = new DBReadOperation<PersonDetails>();
The MappingClass would take in a DBReadOperation and return a T. It could be used like:
var mapper = new MappingClass<DBReadOperation<PersonDetails>>();
Collection<PersonDetails> collection = mapper.MapData(someArgument);
精彩评论