我有下面的类:使用通用型“映射<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);
使用工厂类工作正常...
- 如何解决与第一个版本的问题?
- 我应该在Mapper中使用方法还是使用工厂?
我这样做只是因为我有类型是匿名的情况。
为什么你需要在第一个例子'TKey'? –
@YacoubMassad只是添加了缺少的Add方法,这就是我使用TKey的原因。 –
你仍然不需要'GetFor'方法中的'TKey'。 – DavidG