C# Polymorphism

后端 未结 4 1977
难免孤独
难免孤独 2020-12-25 10:19


What\'s the difference between run-time polymorphism and compile-time polymorphism? Also, what\'s the difference between early binding and late binding? Examples woul

4条回答
  •  难免孤独
    2020-12-25 10:37

    Compile Time Polymorphism

    Method overloading is a great example. You can have two methods with the same name but with different signatures. The compiler will choose the correct version to use at compile time.

    Run-Time Polymorphism

    Overriding a virtual method from a parent class in a child class is a good example. Another is a class implementing methods from an Interface. This allows you to use the more generic type in code while using the implementation specified by the child. Given the following class definitions:

    public class Parent
    {
        public virtual void SayHello() { Console.WriteLine("Hello World!"); }
    }
    
    public class Child : Parent
    {
        public override void SayHello() { Console.WriteLine("Goodbye World!"); }
    }
    

    The following code will output "Goodbye World!":

    Parent instance = new Child();
    instance.SayHello();
    

    Early Binding

    Specifying the type at compile time:

    SqlConnection conn = new SqlConnection();
    

    Late Binding

    The type is determined at runtime:

    object conn = Activator.CreateInstance("System.Data.SqlClient.SqlConnection");
    

提交回复
热议问题