C#对象实例化
C#常用的对象实例化有以下几种方式:
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Demo { class Program { static void Main(string[] args) { //通过new实例化 Calculate calc = new Calculate(); Console.WriteLine(calc.AddOne(0)); //通过Activator实例化 ICalculate calc2 = Activator.CreateInstance<Calculate>(); Console.WriteLine(calc2.AddOne(1)); ICalculate calc3 = (Calculate)Activator.CreateInstance(Type.GetType("Demo.Calculate")); Console.WriteLine(calc3.AddOne(2)); //通过Assembly实例化 ICalculate calc4 = (Calculate)Assembly.GetAssembly(Type.GetType("Demo.Calculate")).CreateInstance("Demo.Calculate"); Console.WriteLine(calc4.AddOne(3)); //Type.GetType("Demo.Calculate")也可以写成typeof(Calculate) } } public class Calculate : ICalculate { public int AddOne(int a) { return a + 1; } } public interface ICalculate { int AddOne(int a); } }