泛型和继承问题

发布于 2024-10-09 11:48:52 字数 724 浏览 1 评论 0原文

我很想说这个问题与我的一般架构有关,但无论哪种方式,作为示例显示可能比描述更容易。

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'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 :-).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坠似风落 2024-10-16 11:48:52

这是因为您有两个类型参数,但方法签名中只有一个,因此它无法推断出两者。另一个则不需要。将方法签名更改为:

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

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!
}
几味少女 2024-10-16 11:48:52

你可能知道,他们需要工作。原因是 ManagerAbc 不是 ManagerBase 类型。通用部分属于同一类型并没有帮助。您可以尝试更改为:

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

That want work, as you probably know. The reason is that ManagerAbc is not of type 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文