C#早期绑定&后期绑定

早期绑定(early binding),又可以称为静态绑定(static binding)。在使用某个程序集前,已知该程序集里封装的方法、属性等。则创建该类的实例后可以直接调用类中封装的方法。

后期绑定(late binding),又可以称为动态绑定(dynamic binding),需要使用System.Reflection,动态地获取程序集里封装的方法、属性等。

Example: 在命名空间Binding中有一个Employee类,代码如下:

public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public float Salary { get; set; }

        public Employee()
        {
            ID = -1;
            Name = string.Empty;
            Salary = 0;
        }
        public Employee(int id, string name, float salary)
        {
            ID = id;
            Name = name;
            Salary = salary;
        }
        public void DisplayName()
        {
            Console.WriteLine("Name : " + Name);
        }
        public void PrintSalary()
        {
            Console.WriteLine("Salary : " + Salary);
        }
        public void displayemp(string name)
        {
            Console.WriteLine("Name : " + name);
        }

    }

早期绑定是已知该类中的属性和方法,只要实例化类后,可以直接调用类中的方法,如下所示:

class Program
    {
        static void Main(string[] args)
        {
            // Early Binding
            Employee employee = new Employee();
            employee.Name = "Larissa";
            employee.ID = 64;
            employee.Salary = 3000;

            employee.DisplayName();
            employee.PrintSalary();

            Console.Read();
        }
    }

后期绑定需要使用System.Reflection获取类中的方法和属性。这种后期绑定的方法大量的被使用在IDE和UI设计中,如下所示:

class Program
    {
        static void Main(string[] args)
        {
            Type _type = Type.GetType("Binding.Employee");
            Console.WriteLine(_type.FullName);
            Console.WriteLine(_type.Namespace);
            Console.WriteLine(_type.Name);

            PropertyInfo[] info = _type.GetProperties();
            foreach(PropertyInfo propinfo in info)
            {
                Console.WriteLine(propinfo.Name);
            }

            MethodInfo[] methods = _type.GetMethods();
            foreach(MethodInfo methodinfo in methods)
            {
                Console.WriteLine(methodinfo.ReturnType.Name);
                Console.WriteLine(methodinfo.Name);
            }

            Console.Read();
        }
    }

运行结果如图所示:

早期绑定易于开发且会比后期绑定运行的更快,因为不需要类型转换。此外早期绑定中出错的可能性较小。后期绑定的优点是可以保存对任何对象的引用。

 参考文献:https://www.codeproject.com/Tips/791017/Reflection-Concept-and-Late-Binding-in-Csharp

原文地址:https://www.cnblogs.com/larissa-0464/p/11120737.html