简体   繁体   English

覆盖C#中的通用方法

[英]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 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 现在我很困惑,因为我的以前的问题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): 有效调用(如果S是此范围内先前定义的类型参数):

DoSomething<S>(input);

Valid invocation (since type parameter T can be inferred from the argument input ): 有效调用(由于可以从参数input推断类型参数T ):

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. 链接的代码将覆盖返回T的方法签名,没有返回T的参数,没有参数。 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. 链接的问题尝试使用Document<type1, type2>覆盖Document<T, U>的返回值,该返回值本身是无效的,这是因为通用括号中不允许使用类型,但也是无效的,因为该覆盖更改了方法签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM