zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    26.列表的循环遍历
    效率比较--链表
    心之距离 再回首 光年之遥远
    效率比较--集合
    效率比较--数组
    哈希表
    栈 VS 队列
    struts1 标签引入
    web 连接池配置
    zip&ftp命令
  • 原文地址:https://www.cnblogs.com/MrHacker/p/4363143.html
Copyright © 2011-2022 走看看