简体   繁体   中英

Understanding C# generic and upcasting

Please see following examples:

class A : ISomething
class B : ISomething
class C : ISomething

private void AcceptsISomething<T>(T input) where T : ISomething
{
    if (input is A)
    if (input is B)
    if (input is C)
}

private void AcceptsISomething(ISomething input)
{
    if (input is A)
    if (input is B)
    if (input is C)
}

What's the difference of functionality between above two examples?

I think there is no difference because both function ensures that input has implemented ISomething , and in both function input can be successfully pattern-matched to the types which implements ISomething .

But I also think that if there were really no difference, then there would be no reason for the lauguage feature where to exist.

Well in your example there actually is no difference, but the WHERE constraint for generics is indeed very useful. By adding a WHERE constraint to a generic function, you can ensure that the used type is derived (or is) the the type in the constraint. By this, you also can use functions of this type.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters

Your example is very simple, but in general there are a lot of things you can do with where only:

Multiple constraints

void AcceptsISomething<T>(T input) where T : ISomething, new()

Inheritance

class Base<T> where T : ISomething

class ChildA : Base<A>

Return value

private T Modify<T>(T input) where T : ISomething

var value = new A();
value = Modify(value); // vs (A)Modify(value)

Concrete type

private void AcceptsISomething<T>(T input) where T : ISomething
{
    Console.WriteLine(typeof(T));
}

A value = null;
AcceptsISomething(null); // prints "A" although argument is null

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