简体   繁体   中英

Override generic methods in c#

I thought I can not override generic methods of a derived class.

http://my.safaribooksonline.com/book/programming/csharp/9780071741163/generics/ch18lev1sec13

The code in this link runs fine. The overriden method is called although the instance type of

the base class is used and not the instance of the derived type.

Now I am confused because a former question of mine Type parameter declaration must be identifier not a type

is about calling the overriding generic method with the instance of base type which did NOT work!

When you declare a method, you need to use a type parameter. When you invoke a method you use either a type parameter or a type, depending on if you're programming generically.

Valid declaration:

void DoSomething<T>(T input)
{
 ...
}

Invalid declaration:

void DoSomething<int>(T input)
{
 ...
}

Valid invocation:

DoSomething<int>(input);

Valid invocation (if S is a type parameter previously defined in this scope):

DoSomething<S>(input);

Valid invocation (since type parameter T can be inferred from the argument input ):

DoSomething(input);

The problem is simple confusion over method signatures and declarations. The linked code is overriding a method signature of return T, no parameters with return T, no parameters. This is perfectly fine as the method signatures are the same.

The linked question attempts to override a return of Document<T, U> with Document<type1, type2> , which is invalid in and of itself due to types not being permitted in generic brackets, but also invalid because the override changes the method signature.

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