c# - Overriding method to change return type -


I have a situation in which I want to override a base class method so that the type of return is slightly Way to change By making a slight change I mean that an object has to be withdrawn which comes from the object that would be returned by default in the method ... in fact, a little code will make it easier ...

  class program {static zero main (string [] args) {var obj = new ParentClass (); Console.light line ("Parents say:" + obj.ShowYourHand ()); Var obj2 = new child class (); Console.lightline ("kids say:" + obj2.ShowYourHand ()); Console.ReadLine (); }} Public class ParentClass {public string ShowYourHand () {var obj = GetExternalObject (); Return obj.ToString (); } Secure Virtual ExternalObject GetExternalObject () {New ExternalObject () Return; }} Public Class ChildClass: ParentClass {Protected Virtual New ExternalObjectStub GetExternalObject () {New ExternalObjectStub (); }} Public class external object {public override string toasting ()} return "external object"; }} Public class external object stub: External object {public override string toasting (return) {return "external object stub"; I have this issue that obj2 example does not call the version of GetExternalObject (), but its use implies parental implementation.  

I think this is because in the code

  var obj = GetExternalObject ();   

The type of objection is expected to be ExternalObject in the orbit class. I understand that C # can not distinguish between methods based on return type.

I know that there are other solutions to this issue, such as defining an IExternalObject, so it does not get locked about. What was the one I wanted to know was thinking that the child classes prevent GetExternalObject from being called from the Child Category?

Am I completely foolish? : -)

Or am I totally foolhardy? : -)

Yes, you are you can not change the return type method by overriding it. I can not understand it in my sample anyway. Just leave the return type, as it was and return a new external object stub . This works, because the external object stub is derived from to the external object .

Type the base member by hiding it with new , as you do, generally it is a very bad idea because it leads to such a class Which can not be used in a polymorphic manner. This is exactly what you are experiencing here: If the reference is the type of variable holding ParentClass , then this method calls in ParentClass , even though the example actually In ChildClass , does not provide an override implementation of ChildClass GetExternalObject .

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -