|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Overriding generic methods - compiler hides wrong methodin an inherited class. I have a base class with a non-generic method "Foo(string arg)" and a generic method "Foo<T>(T arg)" (identical names). Now I create a new class that inherits from that base class. In this class I override the generic Foo<T> method (using "new"). If I make a call from the inherited class to this.Foo("abc") (which should invoke the non generic method in the base class, as that method is not overridden), something strange happens: Not the non-generic method in the base class, but the generic method in the derived class is invoked. The problem only occurs if I hide a method using new. If I override a virtual method, everything is fine. To clarify, consider the following 3 classes and the comments behind the code with the strange behavior: public class Base { public Base() {} public int Foo(string arg) { return 1; } public bool Foo<T>(T arg) { return false; } public bool Boo(string arg) { return true; } public bool Boo<T>(T arg) { return false; } } public class Derived : Base { public Derived() :base() {} public new bool Foo<T>(T arg) { string s = ""; int i1 = this.Foo(s); // Does not compile (expects bool) ! int i2 = base.Foo(s); // OK (calls Base.Foo(string arg)) int i3 = ((Base)this).Foo(s); // OK (calls Base.Foo(string arg)) return base.Foo<T>(arg); // OK (calls Base.Foo(T arg)) } public new bool Boo<T>(T arg) { string s = ""; bool b1 = this.Boo(s); // StackOverflowException (calls Derived.Boo<T>(T arg)) ! bool b2 = base.Boo(s); // OK (calls Base.Boo(string arg)) bool b3 = ((Base)this).Boo(s); // OK (calls Base.Boo(string arg)) return base.Boo<T>(arg); // OK (calls Base.Boo<T>(T arg)) } } public class Derived2 : Derived { public Derived2() : base() {} public new bool Foo<T>(T arg) { string s = ""; int i1 = this.Foo(s); // Does not compile (expects bool) ! int i2 = base.Foo(s); // Does not compile (expects bool) ! int i3 = ((Base)this).Foo(s); // OK (calls Base.Foo(string arg)) return base.Foo<T>(arg); // OK (calls Derived.Foo(string arg)) } public new bool Boo<T>(T arg) { string s = ""; bool b1 = this.Boo(s); // StackOverflowException (calls Derived2.Boo<T>(T arg)) ! bool b2 = base.Boo(s); // StackOverflowException (calls Derived.Boo<T>(T arg)) ! bool b3 = ((Base)this).Boo(s); // OK (calls Base.Boo(string arg)) return base.Boo<T>(arg); // StackOverflowException (calls Derived.Boo<T>(T arg)) ! } } Is this a bug or a wanted feature? Thanks in advance for helping. |
|||||||||||||||||||||||