2016-06-10 84 views
0

我有下面的類:使用通用型「映射<T>」需要1個類型參數

public class Mapper<T> { 

    public static Mapper<T> GetFor<TKey>(T type) { 
    return new Mapper<T>(); 
    } 

    public static Mapper<T> GetFor<TKey>(IEnumerable<T> types) { 
    return new Mapper<T>(); 
    } 

    public Mapper<T> Add<TKey>(Expression<Func<T, TKey>> expression, String name) { 

    _fields.Add(name, expression); 
    return this; 

    } 

} 

我使用的是靜態方法,有時我需要創建具有匿名類型映射器實例,所以我用:

var a = new { /* ... */ } 
var b = Mapper.GetFor(a); 

但我得到的錯誤:

Using the generic type 'Mapper<T>' requires 1 type arguments 

我也試過如下:

public class MapperFactory { 
    public static Mapper<T> CreateMapperFor<T>(IEnumerable<T> typeProvider) { 
    return new Mapper<T>(); 
    } 
} 

var a = new { /* ... */ } 
var b = MapperFactory.CreateMapperFor(a); 

使用工廠類工作正常...

  1. 如何解決與第一個版本的問題?
  2. 我應該在Mapper中使用方法還是使用工廠?

我這樣做只是因爲我有類型是匿名的情況。

+3

爲什麼你需要在第一個例子'TKey'? –

+0

@YacoubMassad只是添加了缺少的Add方法,這就是我使用TKey的原因。 –

+2

你仍然不需要'GetFor'方法中的'TKey'。 – DavidG

回答

2

有沒有這樣的班級爲Mapper,只有Mapper<T>,所以你不能在這樣一個不存在的類上調用靜態方法(即Mapper.GetFor不能解析)。

您需要爲此創建非通用助手類:所以現在你可以

public class Mapper 
{ 
    public static Mapper<T> GetFor<T>(T templateObject) 
    { 
     return new Mapper<T>(); 
    } 
} 

var x = new{a = 1, b = 2}; 
var mapper = Mapper.GetFor(x); 
2

How to solve the problem with the first version?

你不知道。要在泛型類中調用靜態方法,您需要指定泛型類型參數。

Should I have a method inside Mapper or use a factory?

使用非通用工廠類。如果你願意,你可以簡單地打電話給你的工廠類Mapper。這就是.NET框架所要做的:

  • Tuple<T1, T2>是一個泛型類。
  • Tuple是包含static factory methodCreate<T1, T2>(T1 item1, T2 item2)的工廠類。
+0

請問您,請用一些代碼澄清? –

+1

@MiguelMoura:哪一部分?你的工廠班很好!如果你想遵循Tuple使用的模式,只需用'Mapper'替換上一個代碼示例中的MapperFactory。但是,將MapperFactory稱爲MapperFactory也沒什麼問題:它更加明確,而且這是您通常在Java代碼中執行的操作。 – Heinzi

+1

即將說出同樣的內容,但沒有非常好的Tuple示例。 – Chris

0

@ Heinzi是對的,你不能這樣做,最好使用在非泛型類中聲明的工廠方法。如果你真的想用MapperTypeName(雖然我不認爲這是一個很好的做法),你可以定義static class Mapper和申報方法有

public static class Mapper 
{ 
    public static Mapper<T> GetFor<T>(T type) 
    { 
     return new Mapper<T>(); 
    } 
} 
相關問題