[英]C# Generic type constraint muddle
I am having trouble with a generic type constraint. 我在泛型类型约束方面遇到麻烦。 I have the below method, and im struggling to pass anything into the childSegments parameter, the first parameter i can get round.
我有以下方法,并且我正在努力将任何内容传递给childSegments参数,我可以获取第一个参数。
private void FillSegment<T, TT>(BaseSegment<T> segment, IEnumerable<BaseSegment<TT>> childSegments)
where T : class
where TT : class
{}
TT is of type class, but the list im trying to pass in, should be a combination of different classes not just a single class type, that's the wall i am hitting. TT是类型类,但是试图传递的列表应该是不同类的组合,而不仅仅是单个类类型,这就是我要碰到的墙。 I could just pass in this list:
我可以通过以下列表:
List<BaseSegment<Lead>> l = new List<BaseSegment<Lead>>();
but like i said, i need to pass in multiple classes, i have a LeadSegment, AccountSegment, ContactSegment etc (which implement BaseSegment<T>
). 但是就像我说的那样,我需要传递多个类,我有一个LeadSegment,AccountSegment,ContactSegment等(实现
BaseSegment<T>
)。
The ideal scenario would be something like this: 理想的情况是这样的:
List<BaseSegment<T>> lst = new List<BaseSegment<T>>();
lst.Add(LeadSegment);
lst.Add(AccountSegment);
lst.Add(ContactSegment);
..and pass that, but you cannot create a list with a <T>
type within a method or outside i believe ..并通过它,但是我不能在方法内部或外部创建带有
<T>
类型的列表
Any Ideas? 有任何想法吗?
Thanks 谢谢
Make BaseSegment
a non-generic abstract class (you don't ever instantiate BaseSegment
directly do you?). 使
BaseSegment
成为非泛型抽象类(您从未直接实例化BaseSegment
吗?)。 Your signature for FillSegment
could then look like this: 您对
FillSegment
签名如下所示:
private void FillSegment<TParent>(TParent parent, IEnumerable<BaseSegment> children)
where TParent : BaseSegment
This enables you to consume the method like this: 这使您可以使用如下方法:
var parent = new SomeParentSegment(); // SomeParentSegment derives from BaseSegment
var children = new List<BaseSegment>();
children.Add(new LeadSegment()); // LeadSegment derives from BaseSegment
children.Add(new AccountSegment()); // AccountSegment derives from BaseSegment
children.Add(new ContactSegment()); // ContactSegment derives from BaseSegment
FillSegment(parent, children);
Note that this allows children
to be of the same type as parent
, given that both instances derive from BaseSegment
. 请注意,鉴于两个实例均源自
BaseSegment
,因此这允许children
与parent
具有相同的类型。
I'm having a little trouble following what you are wanting to do, but I think you want to make your constraints 我在遵循您要执行的操作时遇到了一些麻烦,但我认为您想约束自己
where TT : T
or... 要么...
where TT : BaseSegment<T>
Both of these scenarios enable your "Ideal scenario" above; 这两种方案都可以启用上面的“理想方案”; but without a further understanding...
但没有进一步的了解...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.