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);
}
}
總結
- 上一篇: 中文搜索引擎技术揭密:排序技术 (转)
- 下一篇: 设计模式(十三):从“FQ”中来认识代理