简体   繁体   中英

C# How to cast a generic type to interface it implements

This might be a silly question but I couldn't find a solution for it.

I have this structure (simplified for brevity):

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>
        }
    }
}

I guess I cannot convert a generic type to an interface, but how can I achieve this? I could write RegisterConfiguration as:
public void RegisterConfiguration(string name, Configuration<IEntity> configuration) , but then it would fail when I call it with one of my entities (even if they all implement IEntity ).

There must be something I did not understand properly with generics but I can't figure out what.

Try like this:

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);
  }
}

This should work: Reason is you can cast from template to a interface but not reverse and also at class level it should know the template definition

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>
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM