2014-09-22 113 views
0

我試圖將我的AutoMapper代碼轉換爲更流暢的API,例如 現有代碼:將對象轉換爲泛型類型 - automapper靜態擴展

Model.Foo target = Mapper.Map<Contract.Foo, Model.Foo>(source); 

我想什麼的代碼看起來是這樣的

Model.Foo target = source.ConvertTo<Model.Foo>(); 

我開始寫我的擴展方法,但我似乎無法得到這個工作。

public static class AutoMapperConverterExtension 
{ 
    public static T ConvertTo<T>(this string source) where T : new() 
    { 
     Type sourceType = Type.GetType(source); 
     if (IsMapExists<sourceType, T>()) // complains here! cannot resolve 'sourceType'. If I use inline, won't compile. 
     { 
      return Mapper.Map<T>(source);  
     } 
     throw new NotImplementedException("type not supported for conversion"); 
    } 

    public static bool IsMapExists<TSource, TDestination>() 
    { 
     return (AutoMapper.Mapper.FindTypeMapFor<TSource, TDestination>() != null); 
    }   
} 
+0

,並且您實施有什麼問題? – Servy 2014-09-22 18:57:26

+0

*抱怨這裏*關於什麼? – 2014-09-22 18:59:17

+0

更新後 - 基本上不會編譯。 – Raymond 2014-09-22 19:19:51

回答

3

看起來你是過於複雜的事情,你也許能矇混過關:

public static T ConvertTo<T>(this object source) 
{ 
    return Mapper.Map<T>(source); 
} 

這就是說,你不能使用你正在試圖做仿製藥代碼發佈。 sourceType是一個運行時變量,不能用於在編譯時確定的泛型類型參數。在這種情況下,AutoMapper提供了一個可以使用的非通用版本FindTypeMapFor()

你也不能認爲source將會是一個字符串參數。你可能想要一個object

public static T ConvertTo<T>(this object source) where T : new() 
{ 
    Type sourceType = Type.GetType(source); 
    if (IsMapExists(sourceType, typeof(T))) 
    { 
     return Mapper.Map<T>(source); 
    } 
    throw new NotImplementedException("type not supported for conversion"); 
} 

public static bool IsMapExists(Type source, Type destination) 
{ 
    return (AutoMapper.Mapper.FindTypeMapFor(source, destination) != null); 
} 
2

在調用泛型函數時,引發錯誤的行需要更改爲使用反射。

var method = typeof(AutoMapperConverterExtension).GetMethod("IsMapExists"); 
var generic = method.MakeGenericMethod(sourceType, typeof(T)); 

bool exists = Convert.ToBoolean(generic.Invoke(null, null)); 

if (exists) 
{ 
    return Mapper.Map<T>(source);  
} 

How do I use reflection to call a generic method?

+0

謝謝,我學到了一些新東西,但我標出了另一個答案是正確的,因爲它更好地解決了我面臨的問題。 – Raymond 2014-09-22 21:40:02