C#如何将泛型转换为实现的接口

时间:2019-10-11 08:00:44

标签: c# oop generics interface

这可能是一个愚蠢的问题,但我找不到解决方案。

我有这样的结构(为简便起见简化):

namespace Test
{
    public interface IEntity
    { }

    public class BaseEntity : IEntity 
    { }

    public class OneEntity : BaseEntity
    { }

    public class Configuration<T> where T : IEntity 
    {

    }

    public class Service 
    {
        public Dictionary<string, Configuration<IEntity>> Configurations = new Dictionary<string, Configuration<IEntity>>();

        public void RegisterConfiguration(string name, Configuration<T> configuration) where T : IEntity
        {
            if(Configurations.ContainsKey(name))
                return;

            Configurations.Add(name, configuration); //Error: Unable to convert Configuration<T> to Configuration<IEntity>
        }
    }
}

我想我无法将泛型转换为接口,但是如何实现呢?我可以这样写RegisterConfiguration
public void RegisterConfiguration(string name, Configuration<IEntity> configuration),但是当我用我的一个实体调用它时,它会失败(即使它们都实现了IEntity)。

使用泛型某些东西我可能无法正确理解,但我不知道是什么。

2 个答案:

答案 0 :(得分:3)

尝试这样:

public class Service<T> where T : IEntity
{
  public Dictionary<string, Configuration<T>> Configurations = new Dictionary<string, Configuration<T>>();

  public void RegisterConfiguration(string name, Configuration<T> configuration)
  {
    if (Configurations.ContainsKey(name))
      return;

    Configurations.Add(name, configuration);
  }
}

答案 1 :(得分:0)

这应该有效:原因是您可以将模板从模板转换为接口,但不能反向,并且在类级别它应该知道模板定义

public class Service<T>  where T : IEntity
{
    public Dictionary<string, Configuration<T>> Configurations = new Dictionary<string, Configuration<T>>();

    public void RegisterConfiguration(string name, Configuration<T> configuration) 
    {
        if (Configurations.ContainsKey(name))
            return;

        Configurations.Add(name, configuration); //Error: Unable to convert Configuration<T> to Configuration<IEntity>
    }
}