简体   繁体   中英

C# - Overriding the return type from interface with a derived type using generics

My goal is to have a dictionary which stores different Container objects that derive from a interface IContainer. The user can add different Container objects (as long as they implement IContainer) to this dictionary. The containers can add elements related to the container (eg configContainer will add configElements, diContainer will add diConfigElements).

The elements also implement from a interface. I want to avoid the scenario of DiConfigElements being added to ConfigContainer. I have looked at related questions and they dont quite solve my problem. I feel that generics will solve my problem, I have a example but I get Argument 2: cannot convert from 'ConfigContainer' to 'IContainer' I am using Unity C#.

test.cs

using System.Collections;
using System.Collections.Generic;

public class test
{
    public Dictionary<string, IContainer<IResolveableItem>> containers;
    // Use this for initialization
    void Start()
    {
        containers = new Dictionary<string, IContainer<IResolveableItem>>();
        ConfigContainer configContainer = new ConfigContainer();
        ConfigContainerElement configElement = new ConfigContainerElement();
        configElement.Name = "configTest";
        configElement.Path = "configTest/configTest";
        configContainer.Add("test1", configElement);

        containers.Add("config",configContainer);
    }
}

IContainer.cs

using System.Collections;

public interface IContainer<T> where T : IResolveableItem
{
    void Add(string key , T value);
}

ConfigContainer.cs

using System.Collections.Generic;

public class ConfigContainer : IContainer<ConfigContainerElement>
{
    public Dictionary<string, IResolveableItem> container = new Dictionary<string, IResolveableItem>();

    public void Add(string key, ConfigContainerElement value)
    {
        throw new System.NotImplementedException();
    }
}

ConfigContainerElement.cs

using System.Collections;

public class ConfigContainerElement : IResolveableItem
{
    protected string name;
    protected string path;

    public string Name
    {
        get
        {
            return name;
        }

        set
        {
            name = value;
        }
    }

    public string Path
    {
        get
        {
            return path;
        }

        set
        {
            path = value;
        }
    }
}

IResolveableItem.cs

using System.Collections;

public interface IResolveableItem
{
    string Name { get; set; }
    string Path { get; set; }
}

这是泛型的局限性,必须使用运行时检查。

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