其他分享
首页 > 其他分享> > 反射

反射

作者:互联网

新建一个控制台应用程序

 

 Bike中的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 反射
{
    public class Bike : ICar
    {
        public void Light()
        {
            Console.WriteLine("我有1个灯");
        }

        public void Wheel()
        {
            Console.WriteLine("我有2个轮子");
        }
    }
}
View Code

Car中的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 反射
{
    public class Car : ICar
    {
        public void Light()
        {
            Console.WriteLine("我有8个灯");
        }

        public void Wheel()
        {
            Console.WriteLine("我有4个轮子");
        }
    }
}
View Code

Factory中的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//引用配置和反射
using System.Configuration;
using System.Reflection;
namespace 反射
{
    public class Factory
    {
        private static string InterfaceName = ConfigurationManager.AppSettings["InterfaceName"];

        public ICar GetCar()
        {
            //第一个是程序集名称,第二个是命名空间.类名
            return (ICar)Assembly.Load("反射").CreateInstance("反射" + "." + InterfaceName);
        }
    }
}
View Code

ICar中的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 反射
{
    public interface ICar
    {
        void Wheel();
        void Light();

    }
}
View Code

Program中的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 反射
{
    class Program
    {
        static void Main(string[] args)
        {
            Factory factory = new Factory();
            ICar Result = factory.GetCar();
            Result.Light();
            Result.Wheel();
            Console.ReadLine();
        }
    }
}
View Code

App.config中的配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>

  <appSettings>
    <add key="InterfaceName" value="Car" />      
  </appSettings>
  
  
</configuration>
View Code

 

标签:反射,Code,void,ICar,System,using,public
来源: https://www.cnblogs.com/Luck1996/p/12005566.html