A type cannot be used as a parameter of type 'T' in a generic type or method - Why?

I am trying to inherit two different models from an interface. These models must be passed either as a list or as a collection to a method. Now I get this error message:

The type 'InheritanceTest.FooModel' cannot be used as type parameter 'T' in the generic type or method 'InheritanceTest.Service.DoSomethingWith<T>(System.Collections.Generic.IEnumerable<T>)'. There is no implicit reference conversion from 'InheritanceTest.FooModel' to 'InheritanceTest.IModel<InheritanceTest.IModelItem>'. C:\Work\InheritanceTest\InheritanceTest\Program.cs 14 13 InheritanceTest

Can someone please explain to me what I'm doing wrong ?: D

Demo code:

interface IModel<T> where T : IModelItem
{
    string Name { get; set; }

    IEnumerable<T> Items { get; set; }
}

interface IModelItem
{
    string Name { get; set; }
}

class FooModel : IModel<FooModelItem>
{
    public FooModel()
    {
        Items = new List<FooModelItem>();
    }

    public string Name { get; set; }
    public IEnumerable<FooModelItem> Items { get; set; }
}

class FooModelItem : IModelItem
{
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var fooLists = new List<FooModel>();
        var barLists = new ObservableCollection<BarModel>();

        var service = new Service();

        service.DoSomethingWith(fooLists);
        service.DoSomethingWith(barLists);
    }
}

class Service
{
    public void DoSomethingWith<T>(IEnumerable<T> list) where T : IModel<IModelItem>
    {
        foreach (var model in list)
        {
            Debug.WriteLine(model.Name);

            foreach (var item in model.Items)
            {
                Debug.WriteLine(item.Name);
            }
        }
    }
}

The demo project can be found on GitHub: https://github.com/SunboX/InheritanceTest/blob/master/InheritanceTest/Program.cs

+4
source share
1 answer

, , , FooModel FooModelItem BarModelItem. , :

IModel<FooModelItem> fooModel = new FooModel();
IModel<IModelItem> iModel = fooModel;
iModel.Items = new List<BarModelItem>(new BarModelItem());

FooModelItem fooModelItem = fooModel.Items.First();

, , , , FooModelItem, BarModelItem!

, , - . , IModel<FooModelItem> IModel<IModelItem>, FooModelItem : IModelItem. - , .

, , , .

+4

Source: https://habr.com/ru/post/1546842/


All Articles