接口(interface)上的 C# 泛型

标签 c# generics

我正在创建一个通用接口(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/

相关文章:

c# - 无法加载文件或程序集 'Microsoft.Build.Framework' (VS 2017)

c# - 无法将 TextMeshPro 文本获取到 Unity 中的变量槽

java - 通用列表打印方法

java逆变疑问

java - 如何根据构造函数值获取枚举实例并进行一般转换?

c# - 使用 PC 上已有的 Oracle.DataAccess.DLL,不提供

c# - Stackalloc 和值类型

c# - 如何使用 SSIS C# 脚本组件将程序集文件加载到 Azure 数据工厂集成运行时?

java - 抽象泛型类中的静态变量

c# - 泛型类作为返回类型