简体   繁体   English

泛型和继承问题

[英]Generics and Inheritance Problem

I'm tempted to say this problem is with my general architecture but either way it's probably easier to show as an example than it would be to describe. 我很想说这个问题与我的通用体系结构有关,但是无论哪种方式,作为示例进行展示都可能比描述起来容易。

public class AppUserBase
{
}

public class AppUserAbc : AppUserBase
{
}

public class ManagerBase<T> where T : AppUserBase
{
    protected AppUserCollection<T> _users = new AppUserCollection<T>();
}

public class ManagerAbc : ManagerBase<AppUserAbc>
{

}

public static class Program
{
    public static void Main()
    {
        ManagerAbc x = new ManagerAbc();
        DoSomething(x); //fails
    }

    public static void DoSomething<M,U>(ManagerBase<AppUserBase> manager) where M : ManagerBase<U> where U : AppUserBase
    {
        //do something!
    }
}

I hope what I'm trying to do is easy to see and what I should be doing is even easier to explain to me :-). 我希望我想做的事情很容易理解,我应该做的事情甚至更容易向我解释:-)。

It's because you have two type parameters but only one is in the method signature, so it can't infer both. 这是因为您有两个类型参数,但是方法签名中只有一个,因此无法同时推断两个参数。 The other is not needed. 另一个不需要。 Change your method signature to: 将方法签名更改为:

public static void DoSomething<U>(ManagerBase<U> manager)
    where U : AppUserBase
{
    //do something!
}

That want work, as you probably know. 您可能知道,那需要工作。 The reason is that ManagerAbc is not of type ManagerBase<AppUserBase> . 原因是ManagerAbc的类型不是ManagerBase<AppUserBase> It doesn't help that the generic part is of the same type. 通用部分是同一类型没有帮助。 You could try to change to: 您可以尝试更改为:

public static void DoSomething<M,U>(ManagerBase<U> manager) where M : Manager<U> where U : AppUserBase

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

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