作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在创建一个通用接口(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/
我是一名优秀的程序员,十分优秀!