C# 使用泛型类型';映射器<;T>';需要1个类型参数
我有以下课程:C# 使用泛型类型';映射器<;T>';需要1个类型参数,c#,C#,我有以下课程: 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 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;
}
}
但我得到了一个错误:
Using the generic type 'Mapper<T>' requires 1 type arguments
使用泛型类型“Mapper”需要1个类型参数
我还尝试了以下方法:
public class MapperFactory {
public static Mapper<T> CreateMapperFor<T>(IEnumerable<T> typeProvider) {
return new Mapper<T>();
}
}
var a = new { /* ... */ }
var b = MapperFactory.CreateMapperFor(a);
公共类MapperFactory{
公共静态映射器CreateMapperf(IEnumerable typeProvider){
返回新映射器();
}
}
var a=new{/*…*/}
var b=MapperFactory.CreateMapperFor(a);
使用factory类可以很好地工作
Mapper
。这就是.NET framework所做的:
是一个泛型类Tuple
是包含Tuple
的工厂类创建(T1项1,T2项2)
Mapper
。这就是.NET framework所做的:
是一个泛型类Tuple
是包含Tuple
的工厂类创建(T1项1,T2项2)
public static class Mapper
{
public static Mapper<T> GetFor<T>(T type)
{
return new Mapper<T>();
}
}
公共静态类映射器
{
公共静态映射器GetFor(T类型)
{
返回新映射器();
}
}
@Heinzi是对的,您不能这样做,最好使用非泛型类中声明的工厂方法。如果您真的想使用<代码>映射器< /代码>作为<代码> TypeName <代码>(虽然我不认为它是一个好的实践),您可以定义<代码>静态类映射器< /> >,并在那里声明方法
public static class Mapper
{
public static Mapper<T> GetFor<T>(T type)
{
return new Mapper<T>();
}
}
公共静态类映射器
{
公共静态映射器GetFor(T类型)
{
返回新映射器();
}
}
没有像映射器那样的类,只有映射器,所以不能对这样一个不存在的类调用静态方法(即Mapper.GetFor
不解析)
您需要为此创建非泛型帮助器类:
public class Mapper
{
public static Mapper<T> GetFor<T>(T templateObject)
{
return new Mapper<T>();
}
}
没有像Mapper
这样的类,只有Mapper
,因此不能对这样一个不存在的类调用静态方法(即Mapper.GetFor
无法解析)
您需要为此创建非泛型帮助器类:
public class Mapper
{
public static Mapper<T> GetFor<T>(T templateObject)
{
return new Mapper<T>();
}
}
为什么在第一个示例中需要TKey
?@YacoubMassad刚刚添加了缺少的Add方法,这就是我使用TKey的原因。在GetFor
方法中仍然不需要TKey
。而且函数中似乎没有使用参数type
。(或类型
)@DavidG您能添加一些代码吗?我不知道你的意思。为什么在第一个示例中需要TKey
?@YacoubMassad刚刚添加了缺少的Add方法,这就是我使用TKey的原因。你仍然不需要GetFor
方法中的TKey
。函数中似乎没有使用参数type
。(或类型
)@DavidG您能添加一些代码吗?我不知道你的意思。@MiguelMoura:哪一部分?你的工厂课很好!如果要遵循Tuple使用的模式,只需将上一个代码示例中的MapperFactory
替换为Mapper
。但是,调用它也没有什么错:它更显式,这是Java代码中通常要做的事情。我正要说同样的话,但没有非常好的元组示例。@MiguelMoura:哪一部分?你的工厂课很好!如果要遵循Tuple使用的模式,只需将上一个代码示例中的MapperFactory
替换为Mapper
。但是,调用它MapperFactory
也没有什么错:它更显式,这是Java代码中通常要做的事情。我也要这么说,但没有非常好的元组示例。