简体   繁体   English

对接口使用约束泛型

[英]Use constraint generic with interface

I have the following code where generic are involved:我有以下涉及泛型的代码:

    public class MyWorkerClass<T> : IWorkerContract<T> //in IWorkerContract also i have same generic constraint that i have in this class.
      where T: INeedAction, new()
    {
        public void DoWork ( T item )
        {
             //Loop on each property of item...
             if ( ..if current property value implement from INeedAction, then condition for recursion.. )
             {
                  this.DoWork ( currentPropertyValue as INeedAction);
                  //Get error -> "Can not convert INeedAction to T"
             }

Basically i have a woker that operate on an object 'A' (that need to implement the interface INeedAction).基本上我有一个在 object 'A' (需要实现接口 INeedAction)上运行的 wker。 If any property of that object 'A' implement the same interface of the object itself (the i INeedAction interface) then i need to recurse with the same DoWork logic on that property too.如果该 object 'A' 的任何属性实现了与 object 本身相同的接口(i INeedAction 接口),那么我也需要在该属性上使用相同的 DoWork 逻辑进行递归。

Strangelly i get that error that i does not understand: "Can not convert INeedAction to T" Why this, if i enforced that T must implement INeedAction?奇怪的是,我得到了我不理解的错误:“无法将 INeedAction 转换为 T” 如果我强制 T 必须实现 INeedAction,为什么会这样?

Let's suppose that Foo and Bar both implement INeedAction , and Foo has a property of type Bar .假设FooBar都实现INeedAction ,并且Foo有一个Bar类型的属性。

Then a MyWorkerClass<Foo> represents a work that is able to DoWork on a Foo .然后一个MyWorkerClass<Foo>代表一个能够在Foo上做DoWork的工作。 So far so good.到目前为止,一切都很好。 However, look what happens when DoWork is called and it finds the Bar property.但是,看看调用DoWork并找到Bar属性时会发生什么。 Since Bar implements INeedAction , you call由于Bar实现INeedAction ,因此您调用

this.DoWork (bar as INeedAction);

Remember that this is still MyWorkerClass<Foo> - a thing that can only do work on Foo , but you are giving it a Bar to work with, That doesn't make sense?请记住, this仍然是MyWorkerClass<Foo> - 只能在Foo上工作的东西,但是你给它一个Bar可以使用,这没有意义吗? does it?可以? This is why you can't pass an INeedWork to a parameter accepting T .这就是为什么您不能将INeedWork传递给接受T的参数的原因。

Note also that DoWork is not generic.另请注意, DoWork不是通用的。 It accepts a very specific type - T .它接受一个非常具体的类型 - T This has to be the same T that is used in the class's type parameter.这必须与类的类型参数中使用的T相同。


Judging from your code, I don't think DoWork should be generic at all.从您的代码来看,我认为DoWork根本不应该是通用的。 It should accept an INeedWork .它应该接受INeedWork

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM