简体   繁体   中英

Type parameters vs. generics

Is there ever a reason to use Type parameters over generics, ie:

// this...
void Foo(Type T);
// ...over this.
void Foo<T>();

It seems to me that generics are far more useful in that they provide generic constraints and with C# 4.0, contravarience and covarience, as well as probably some other features I don't know about. It would seem to me that the generic form has all the pluses, and no negatives that the first doesn't also share. So, are there any cases where you'd use the first instead?

Absolutely: when you don't know the type until execution time. For example:

foreach (Type t in someAssembly.GetTypes())
{
    Foo(t);
}

Doing that when Foo is generic is painful. It's doable but painful.

It also allows the parameter to be null , which can be helpful in some situations.

Well they really aren't the same at all.

With the second one, you've actually got a class of the compile-time type there (whatever has been passed in by whoever). So you can call specific functions on it (say if it's all of some given interface).

In your first example, you've got an object of class 'Type'. So you'll need to still determine what it is and do a cast to do anything useful with it.

Foo(someVariable.GetType());      // allowed

Foo<someVariable.GetType()>();    // illegal

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