Polymorphism, calling the right function
I have a specific function in multi tier class system that is called and it picks the right function when it is called. How do I tell it to pick the function in a specific class?
Please let me know what other information is required from me to get the correct answer as I am not sure if this is enough or开发者_如何学Python too vague. Let me know specifically what I need to provide as I am new to c# as well.
I created the most basic example for polymorphism which I can think of. Try to understand the example and the comments, I will update the post if you have more specific questions.
The first code example contains two classes, the second calls the methods of objects of these classes to demonstrate polymorphism.
public class BaseClass
{
// This method can be "replaced" by classes which inherit this class
public virtual void OverrideableMethod()
{
System.Console.WriteLine("BaseClass.OverrideableMethod()");
}
// This method is called when the type is of your variable is "BaseClass"
public void Method()
{
Console.WriteLine("BaseClass.Method()");
}
}
public class SpecializedClass : BaseClass
{
// your specialized code
// the original method from BaseClasse is not accessible anymore
public override void OverrideableMethod()
{
Console.WriteLine("SpecializedClass.OverrideableMethod()");
// call the base method if you need to
// base.OverrideableMethod();
}
// this method hides the Base Classes code, but it still is accessible
// - without the "new" keyword the compiler generates a warning
// - try to avoid method hiding
// - it is called when the type is of your variable is "SpecializedClass"
public new void Method()
{
Console.WriteLine("SpecializedClass.Method()");
}
}
test the classes using something like this:
Console.WriteLine("testing base class");
BaseClass baseClass = new BaseClass();
baseClass.Method();
baseClass.OverrideableMethod();
Console.WriteLine("\n\ntesting specialized class");
SpecializedClass specializedClass = new SpecializedClass();
specializedClass.Method();
specializedClass.OverrideableMethod();
Console.WriteLine("\n\nuse specialized class as base class");
BaseClass containsSpecializedClass = specializedClass;
containsSpecializedClass.Method();
containsSpecializedClass.OverrideableMethod();
精彩评论