gpt4 book ai didi

C#依赖注入(inject)问题

转载 作者:太空狗 更新时间:2023-10-30 01:27:16 26 4
gpt4 key购买 nike

我有 3 个类:A、B 和 C

所有这些类都实现了一个接口(interface) IMyInterface

我想这样定义接口(interface):

internal IMyInterface<E> where E: class
{
E returnData();
}

这样它就可以返回E类型的数据。类型“E”将是使用 Entity Framework v4 创建的 POCO 对象。

在一个单独的类中,我有:

public class MyClass()
{
IMyInterface<??> businessLogic;

public setBusinessLogic(IMyInterface<E> myObject)
where E : class
{
businessLogic = myObject;
}
}

我试着把 <object>代替 <??>但它无法转换我的 poco 实体类型。

我尝试让我的实体实现一个空接口(interface) IEntity然后使用

IMyInterface<IEntity> businessLogic;
...
businessLogic = new A<POCOObject>();

结果:

 Cannot implicitly convert type
'A<POCOObject>' to
'IMyInterface<IEntity>'. An explicit
conversion exists (are you missing a
cast?)

有什么建议吗?

编辑:我尝试将我的 A、B 和 C 类声明为:

internal class A : IBidManager<EntityObjectType>

internal class A<E> : IBidManager<E> where E : class

导致同样的错误。

最佳答案

它必须是其中之一

public class MyClass<E> where E : IEntity, class
{
IMyInterface<E> businessLogic;

public setBusinessLogic(IMyInterface<E> myObject)
{
businessLogic = myObject;
}
}

 public class MyClass
{
IMyInterface<POCOObject> businessLogic;

public setBusinessLogic(IMyInterface<POCOObject> myObject)
{
businessLogic = myObject;
}
}

如果您希望您的业务对象处理任何 POCO 对象并且它们每个都有一个接口(interface),那么您将需要在类级别指定 where E : class, IEntity。否则你必须为通用 arg 使用具体类型

关于C#依赖注入(inject)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3153863/

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