问题描述
我上课
public class LDBList<T> : List<T> where T : LDBRootClass {
// typical constructor
public LDBList(LDBList<T> x) : base(x) { }
...
}
但是我想拥有一个额外的构造函数,该构造函数接受不同类型的列表(例如A),以及一个将A转换为T并从中构建T列表的函数,例如
but I want to have an extra constructor that takes a list of a different generic type (say A), and a function that converts an A to a T, and build the T list from that, something like
public LDBList(
Func<A, T> converter,
IList<A> aList)
{
foreach (var x in aList) {
this.Append(converter(x));
}
}
因此,converter
的类型为A->T
,因此我将获取一个A
列表并从中创建一个T
列表.我的班级是由T
参数化的,所以很好.
so converter
is of type A->T
so I take an A
list and make a T
list from it. My class is parameterised by T
so that's fine.
但是它抱怨找不到类型或名称空间名称'A'".
But it's complaining "The type or namespace name 'A' could not be found".
好,因此我想在类上需要一个A
通用参数(在构造函数上确实不喜欢它).但是我放在哪里,实际上这甚至有可能吗?
OK, so it needs the an A
generic parameter on the class I suppose (it really doesn't like it on the constructor). But where do I put it, in fact is this even possible?
推荐答案
我不认为您可以向构造函数中添加其他泛型类型.
I don't believe you can add additional generic types to a constructor like that that.
我将重构转换器以进行创建并返回LDBList的实例,这样,转换将充当从A实例创建LDBList的工厂.
I would refactor the converter to do the creation and return the instance of LDBList, that way the convert acts as a factory for creating LDBLists from instances of A.
public class Converter<T,A>
{
public LDbList<T> CreateLdbList(IList<A>) {
var list = new LdbList<T>();
// do the conversion here
return list;
}
}
然后,将用法更改为
var Converter<X,Y> = new Converter();
var result = Converter.Convert(originalData);
这篇关于具有泛型的C#子类化:我需要为ctor提供一个额外的泛型参数,但是如何呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!