简体   繁体   中英

Difference between generic declaration and providing class parameter

What differences are there between declaring:

GenericClass<T> genericInst = new GenericClass<T>();

and

GenericClass<baseClass> temp = new GenericClass<baseClass>();

Here the GenericClass is defined to be for where T : baseClass

GenericClass contains a generic list

private List<T> vals = new List<T>();

It seems to me, and please correct me if I'm wrong, that you are taking 'where T : baseClass' as if it were a default for type T to be a baseClass ?

If so, this is not the case, the specialization where T : baseClass means that the type T must be baseClass or derived from baseClass (or implement if it were an interface instead of a class).

Thus, if you had:

public class GenericClass<T> where T : baseClass
{
}

Then you can say:

var x = new GenericClass<baseClass>();

Or

var y = new GenericClass<SomethignDerivedFromBaseClass>();

But you could not say:

var z = new GenericClass<int>();

Since int does not inherit from baseClass .

The only way to actually use T in the instantiation above is if you were actually calling that line of code from within the GenericClass<T> :

public GenericClass<T> where T : baseClass
{
    void SomeMethod()
    {
        GenericClass<T> genericInst = new GenericClass<T>();
    }
}

Or from another context where T is already known to be a sub-class of baseClass.

UPDATE

Based on your comments, it sounds like you're wondering that if you had:

public class GenericClass<T> where T : baseClass
{
    public List<T> Items { get; set; }

    ...
}

Whether you could add things derived from baseClass into the list, and the answer is yes-ish. The class GenericClass<T> could be declared for any T that inherits from baseClass. But the List<T> would still be strongly typed to type T .

That is given these:

public class BaseClass { }
public class SubClass : BaseClass { }

A GenericClass<BaseClass> could hold both BaseClass and SubClass in it's List<T> since T will be BaseClass .

But a GenericClass<SubClass> will have a List<T> where T will be SubClass and thus can only hold items of SubClass or inheriting from it.

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