我有几个具有相同名称和不同接收参数的扩展方法:
public static List<T>? MapTo<T>(this List<ClassA_DataModel> data) where T : ClassA_BusinessModel, new() { ... }
public static List<T>? MapTo<T>(this List<ClassB_DataModel> data) where T : ClassB_BusinessModel, new() { ... }
... (+50)
用于将不同DataModels之间的mapp(
1:1
)映射到对应的BusinessModels(EDIT1),需要使用反射根据作为参数传入的Listvar businessObjects = (typeof(MapperModel)?.GetMethod(nameof(MapperModel.MapTo))?.MakeGenericMethod(businessModelType).Invoke(null, new[] { dataObjects }) as IList)?.Cast<object>().ToList();
问题是我得到一个异常,因为有不止一个同名的方法:
System.Reflection.AmbiguousMatchException: 'Ambiguous match found'
我的猜测是做这样的事情:
var myMethod = typeof(MapperModel)?.GetMethods().FirstOrDefault(m => m.Name == nameof(MapperModel.MapTo) && m.XXXX == businessModelType);
var businessObjects = (myMethod.MakeGenericMethod(businessModelType).Invoke(null, new[] { dataObjects }) as IList)?.Cast<object>().ToList();
但是我不知道如何让比较部分工作,前提是我必须匹配一个
List<BussinessModel>
.
编辑 我必须对方法使用泛型,而不是像这样声明我的方法(不使用泛型):
public static List< ClassA_BusinessModel>? MapTo(this List<ClassA_DataModel> data) { ... }
因为我稍后也会调用字典,其中将列出很多不同的数据模型:
public static List<T>? MapTo<T>(this Dictionary<Type, IList> dataset) where T : Class36_BusinessModel, new() { ... }
这样我将设法提供从不同
DataModels
到一个BusinessModel
(n:1
)的映射:
List<Class17_DataModel> data17 = (...)
List<Class23_DataModel> data23 = (...)
(...)
var dataset = new Dictionary<Type, IList>()
{
[Class17_DataModel] = data17,
[Class23_DataModel] = data23,
(...)
}
var business17 = data.MapTo<Class17_BusinessModel>();
var business36 = dataset.MapTo<Class36_BusinessModel>();
有什么建议吗? 提前致谢!