简体   繁体   中英

How can I add an ObservableCollection<Class<T>> use inheritance for T

Say I have the following classes:

public class BaseConfig
{
}

public class SpecialConfig : BaseConfig
{
}

Then I have a generic class definition that will contain these:

public class ConfigList<T> : ObservableCollection<T> where T : BaseConfig
{
}

Then I have another class where I want to have a collection of ConfigList objects:

public class ConfigurationManager
{
    private ObservableCollection<ConfigList<BaseConfig>> _configItems

    public ConfigurationManager()
    {
        _configItems = new ObservableCollection<ConfigList<BaseConfig>>();
    }

    public void AddConfigList(ConfigList<BaseConfig> configList)
    {
        _configItems.Add(configList);
    }
}

Then elsewhere in application code I have this:

ConfigurationManager _manager = new ConfigurationManager();
ConfigList<SpecialConfig> _configuration = new ConfigList<SpecialConfig>();

For some odd reason, I thought C# would allow the following due to inheritance, but it doesn't. What I want to know is how can I accomplish adding an object to a collection of a generic type of class like i'm doing below (This is surely a common problem people encounter and surely there's a simple pattern/solution to accomplish this):

_manager.AddConfigList(_configuration);

It will not work this way, but luckily you can work around by taking advantage of co-variance in generic , define one new co-variance interface:

public interface IConfigList<out T>
{
}

So your ConfigList inherits this interface:

public class ConfigList<T> : ObservableCollection<T>, IConfigList<T> 
                                  where T : BaseConfig
{
}

And your ConfigurationManager uses IConfigList instead of ConfigList

public class ConfigurationManager
{
    private ObservableCollection<IConfigList<BaseConfig>> _configItems;

    public ConfigurationManager()
    {
        _configItems = new ObservableCollection<IConfigList<BaseConfig>>();
    }

    public void AddConfigList(IConfigList<BaseConfig> configList)
    {
        _configItems.Add(configList);
    }
}

Then it will work:

 ConfigurationManager _manager = new ConfigurationManager();
 IConfigList<BaseConfig> _configuration = new ConfigList<SpecialConfig>();

 _manager.AddConfigList(_configuration);

您需要利用泛型协方差来实现这一目标。

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