开发者

C# Derived Type to Generic List as Parameter

开发者 https://www.devze.com 2023-01-14 18:09 出处:网络
I am trying to do the following in C# 4.0: I have a Base Class and 2 derived classes public class Base {}

I am trying to do the following in C# 4.0:

I have a Base Class and 2 derived classes


public class Base {}
public class DerivedClass1 : Base {}
public class DerivedClass2 : Base {}

I want to do something like this, but it doesn't work.

How to I tell a Generic List to accept a Base Class and the derived classes of the base class.


public class Class_1
{
    public Class_1()
    {
        List<DerivedClass2> list = new List<Der开发者_运维问答ivedClass2>();
        new Class_2(list);
    }
}

public class Class_2
{
    public Class_2(List<Base> list)
    {

    }
}

In Java I can do something like this


public class Class_2
{
    public Class_2(List<? extends Base> list)
    {

    }
}

Does something like that exists in C#

I hope my question is clear, its just about the generics of the List.

Thanks a lot in Advance :)


General case:

function Foo<T>(List<T> list) where T : Base {
   ...
}

plus for interfaces and delegates, C# allows co/contravariance.

For e.g. IEnumerable<T> and IList<T>, your code will therefore work! Note that if this was allowed for List<T>s, you could insert a Derived1 into a list of Derived2s by using the common base class, which would break type safety. So simply stick to the above, readonly interfaces.


I think you mean either:

// Define other methods and classes here
public class Class_1
{
    public Class_1()
    {
        List<DerivedClass2> list = new List<DerivedClass2>();
        new Class_2<DerivedClass2>(list);
    }
}

public class Class_2<T> where T : Base
{
    public Class_2(List<T> list)
    {

    }
}

Or, if you want the constructor to be generic, and not the class:

// Define other methods and classes here
public class Class_1
{
    public Class_1()
    {
        List<DerivedClass2> list = new List<DerivedClass2>();
        Class_2.Create(list);
    }
}

public class Class_2
{
    public static Class_2 Create<T>(List<T> list) where T : Base
    {
        // Stuff
        return new Class_2(/*Stuff*/);
    }

    public Class_2()
    {

    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消