接口-配置文件

Posted on 2019-12-07 21:06  冰糖Luck1996  阅读(151)  评论(0编辑  收藏  举报

实现功能:通过更改配置文件实现不同的功能

1,创建以下内容

 

 2,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

3,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("我有四个轮子");
        }
    }
}
View Code

4,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("我有一个灯");
        }

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

5,添加引用

 

6,编写配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  
  //下面这一部分
  <appSettings>
    <add key="Icar" value="Bike"/>  
  </appSettings>
  
  
</configuration>
View Code

 

 7,Factory代码

一定要 using System.Configuration;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace 接口配置文件
{
   public  class Factory
    {
        private static string ICar = ConfigurationManager.AppSettings["Icar"];
        public static ICar ObjectFactory()
        {
            if (ICar=="Car")
            {
                return new Car();
            }
            else 
            {
                return new Bike();
            }
               
        }

    }
}
View Code

 

8,程序调用

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

namespace 接口配置文件
{
    class Program
    {
        static void Main(string[] args)
        {
            ICar car = Factory.ObjectFactory();
            car.Light();
            car.wheel();
            Console.ReadLine();
        }
    }
}
View Code

9,更该一些内容即可