gpt4 book ai didi

接口(interface)上的 C# 泛型

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

我正在创建一个通用接口(interface)作为命令模式:

public interface IGenericComponent<T> where T : IVisitableObject
{
void Update(T msg);
}

然后,我将有另一个类,我将持有此接口(interface)的一堆实现(每个都有自己的类型)。在那里我会有一个字典来放置要执行的命令列表,如下所示:

private Dictionary<MessageType, List<IGenericComponent>> _components;

这会产生编译错误,因为我没有输入 IGenericComponent 的类型。我有一个调用 Update 方法的线程和一个订阅方法(向字典中插入一个组件):

public void Subscribe<T>(MessageType messageType, IGenericComponent<T> component) where T : IVisitableObject, new()
{
lock (_monitorDictionary)
{
List<IGenericComponent> subscribedList;
if (_components.TryGetValue(messageType, out subscribedList))
{
subscribedList.Add(component);
IVisitableObject firstUpdate;
if(_messageBuffer.TryGetValue(messageType, out firstUpdate))
component.Update((T)firstUpdate);
}
else
{
subscribedList = new List<IGenericComponent>();
subscribedList.Add(component);
_components[messageType] = subscribedList;
}
}
}

private void ProcessQueue()
{
while (true)
{
IVisitableObject msg;
lock (_monitorQueue)
{
msg = _queue.Dequeue();
}
List<IGenericComponent> components;
lock(_monitorDictionary)
{
components = _components[msg.MsgType];
}
if(components!= null)
{
foreach (IGenericComponent genericComponent in components)
genericComponent.Update(msg);
}
}
}

这段代码无法编译...我来自 Java 编程,在 Java 中,我可以在实例化类型时省略参数化类型。所以...我想知道是否可以在 C# 中执行此操作,因此它会假定它是泛型类型 (IVisitableObject)。或者,如果您知道解决此问题的更好方法...我解决这个问题的方式不是我想要使用的方式。我从接口(interface)中删除了泛型,并使用泛型类型 IVisitableObject 作为 Update 方法的参数。提前致谢。

最佳答案

最简单的解决办法就是说

interface IGenericComponent {
void Update(IVisitableObject msg);
}
interface IGenericComponent<T> : IGenericComponent where T : IVisitableObject {
void Update(T msg);
}

关于接口(interface)上的 C# 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8807069/

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