gpt4 book ai didi

c# - 这是我设计的协变/逆变问题吗?

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:42 26 4
gpt4 key购买 nike

我正在努力解决我认为是我的设计的协变/逆变问题。我想返回一个仅在运行时已知的通用对象。

我有以下类/接口(interface)

public interface IBaseRepository
{
int UserId { get; set; }

// Retrieve
SyncData GetRetrieveData();

// Update
SyncData GetUpdateData();
}

public interface IDomainRepository<T> : IBaseRepository where T : IDomainObject
{
object GetValue(T domainObject, string id);
void SetValue(T domainObject, string id, object value);

// retrieve data
BatchResults<T> Retrieve();

// update data
BatchResults<T> Update(SynchroniseList synchroniseList);
}

我有这些的一些实现:

public abstract class BaseRepository : IBaseRepository
{
public int UserId { get; set; }

public virtual SyncData GetRetrieveData()
{
return new SyncData();
}

public virtual SyncData GetUpdateData()
{
return new SyncData();
}
}

public MyTaskRepository : BaseRepository, IDomainRepository<MyTask>
{
public object GetValue(MyTask domainObject, string id)
{
return domainObject.GetValue();
}

void SetValue(MyTask domainObject, string id, object value)
{
domainObject.SetValue();
}

// retrieve data
public BatchResults<MyTask> Retrieve()
{
// do stuff specific to MyTask
return new BatchResults<MyTask>();
}

// update data
BatchResults<T> Update(SynchroniseList synchroniseList)
{
// do stuff specific to MyTask
return new BatchResults<MyTask>();
}
}

public MyOtherTaskRepository : BaseRepository, IDomainRepository<MyOtherTask>
{
...
}

我遇到的问题是在使用这个存储库时。在我的表格中

IBaseRepository repo = RepositoryFactory.Create(some parameters);

这会返回一个 IDomainRepository,它允许我获取/设置检索/更新数据。

但是,我不知道如何调用检索/更新,因为我无法转换为 IDomainRepository,因为我不知道我将使用哪个域对象。

我一直在阅读协变/逆变,因为我认为它与此有关然而,我也觉得我的设计是错误的,因为我把它弄得太复杂了。我相信我可以在 c# 2.0 中实现它,所以我认为我不应该关心协变/逆变。

是我的设计还是我需要整理我的输入/输出接口(interface)?

最佳答案

改厂返回IDomainRepository<T> ,正如评论者所建议的那样。否则使用 as运算符来强制转换接口(interface)指针:

IBaseRepository repo = RepositoryFactory.Create(...);
IDomainRepository<MyTask> domainRepo = repo as IDomainRepository<MyTask>;
if (domainRepo != nil)
{
// domainRepo implements IDomainRepository<MyTask>.
}

但是测试对象以识别其类型并不鼓励多态行为。

另见 Test if object implements interface .

关于c# - 这是我设计的协变/逆变问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24688839/

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