2016-06-10 86 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>(); 
    } 
} 
相关问题