gpt4 book ai didi

c# - 没有从 T 到 T Base 的隐式引用转换

转载 作者:太空宇宙 更新时间:2023-11-03 22:06:07 28 4
gpt4 key购买 nike

我有两个不同的类派生自一个基类。它们每个都有一个派生自另一个基类的集合,但派生类不同。

class MasterA : MasterBase<ClientA>
class MasterB : MasterBase<ClientB>

public class MasterBase<ClientClass> where ClientClass : ClientBase
{
public List<ClientClass> Clients;
}

Class ClientA : ClientBase
Class ClientB : ClientBase

Class ClientBase

我想要的是拥有一个 UserControl,它可以与任一类型(A 或 B)的主/客户端的父/子列表一起使用。

public class Test<MasterClass> where MasterClass : MasterBase<ClientBase>
{
GenericRepository<MasterClass> repo = new GenericRepository<MasterClass>();
MasterClass master = repo.GetAll;
// do some changes to (base fields of) the master collection and its client collection !
repo.SaveOrUpdate(master);
}

但是....我不能实例化那个测试类..

var t = new Test<MasterA>();
>> There's no implicit reference conversation from MasterA to MasterBase<ClientBase>

那么,有什么方法可以修改 Test 类,使其能够执行我指定的操作吗? 非常感谢一些提示。

最佳答案

不知道您在什么限制下工作,最初将此作为评论发布。

public class Test<MasterClass,U> where MasterClass : MasterBase<U> where U: ClientBase

对您的代码库进行适当的更改?显然,这一行也必须改变:

var t = new Test<MasterA,ClientA>();

问题是,仅仅因为两个类之间存在继承关系,XY ,这并不意味着泛型类型 G<X>G<Y>具有相同(或任何)继承关系。所以MasterBase<ClientA> 继承自MasterBase<ClientBase>

关于c# - 没有从 T 到 T Base<ChildBase> 的隐式引用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8416434/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com