我曾经见过这种使用过的模式/方法,我试图重新创建它以使我现有的一些代码更高效。使用Action委托根据泛型调用正确的函数
用例: 从源系统检索复杂对象。只有一部分信息会被客户端使用,所以我们必须将这个复杂的对象映射到JSON序列化的简单POCO;另外,在这种映射方法中,还有一些其他的数据格式化。首先,我们通过我们的复杂的对象为,做一些基本的处理
// Generic Method, Entry Point for mapping
static void GenericEntry<T, TK>(string userid, string environment, DBContext context) {
.... // do stuff with userid and environment to set a context
.... // query results, which return a complex object of Type TK
// Here is where I would like to use an Action delegate to call the appropriate map
// method.. there could hundreds of objects that map and process down to a POCO,
// Currently, this logic is using reflection to find the appropriate method with
// the appropriate signature... something like:
Type functionType = typeof(DTOFunctions);
var methods = functionType.GetMethods(BindingFlags.Public | BindingFlags.Static);
var mi = methods.FirstOrDefault(x => x.Name == "MapObject" &&
x.ReturnType == typeof(T));
if (mi == null) throw new ArgumentException(string.Format("Unable to find method MapObject for {0}", typeof(TK).Name));
var resultList = new ArrayList();
foreach (var row in results)
{
var poco = mi.Invoke(functionType, new object[] { row });
resultList.Add(poco);
}
if (resultCount == -1) resultCount = resultList.Count;
return SerializeDTO(resultList, ResponseDataTypes.JSON, resultCount);
// THERE HAS TO BE A BETTER WAY STACKOVERFLOW! HALP!
}
public Class DTOFunctions {
// Mapping Method from Complex to Simple object
static SimplePOCO_A MapObject(ComplexObject_A cmplx){
var poco = new SimplePOCO_A();
.... // mapping from cmplx field to SimplePOCO field
}
static SimplePOCO_B MapObject(ComplexObject_B cmplx) {
var poco = new SimplePOCO_B();
.... // mapping from cmplx field to SimplePOCO fiel
}
}
的这另一个方面是,之间的对象的属性名称复杂和简单的对象可能不一样,部分逻辑和目的是制作JSON传递给调用者的包尽可能小。我只想避开任何有关为什么我需要映射功能的问题。 – AnthonyAlmighty 2013-02-12 15:13:44
你有什么理由必须自己编写所有这些吗?你为什么不使用[AutoMapper](https://github.com/AutoMapper/AutoMapper/wiki/Getting-started)? – 2013-02-12 15:14:14
当对象实际上是1对1时,我使用automapper,但是有时候转换过程需要做一些繁重的工作,而且我没有看到Automapper帮助我的方式。尽管这可能完全是我的无知。 – AnthonyAlmighty 2013-02-12 16:23:29