在C#中使用反射的简单例子

目录

介绍

使用代码


介绍

假设我们拥有具有相同功能的不同型号的设备。如何在一个项目中使用它们?在本文中,我们将看到为每个设备模型创建类库,并在反射技术的帮助下在一个项目中使用它们。

使用代码

首先,我们创建名为DeviceCommon的类库项目,并添加包含所有设备逻辑的新接口。

IDevice.cs

/// <summary>
///
/// </summary>
public interface IDevice
{
    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    bool Open();

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    bool Reset();

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    DeviceStatus GetStatus();
    void Initialize();

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    string GetModel();
}

现在,我们为每个设备模型创建类库项目。每个类库包含不同的逻辑和IDevice接口的实现,它将从前一个项目调用。下面是一个合适的代码片段:

此代码片段用于名为Device1” 的模型的设备。

Device1.cs

public class Device1 : IDevice
    {
        public string GetModel()
        {
            return "Device1";
        }

        public DeviceStatus GetStatus()
        {
            throw new System.NotImplementedException();
        }

        public void Initialize()
        {
            throw new System.NotImplementedException();
        }

        public bool Open()
        {
            throw new System.NotImplementedException();
        }

        public bool Reset()
        {
            throw new System.NotImplementedException();
        }
    }

此代码片段用于名为Device2” 的模型的设备。

Device2.cs

public class Device2 : IDevice
    {
        public string GetModel()
        {
            return "Device2";
        }

        public DeviceStatus GetStatus()
        {
            throw new System.NotImplementedException();
        }

        public void Initialize()
        {
            throw new System.NotImplementedException();
        }

        public bool Open()
        {
            throw new System.NotImplementedException();
        }

        public bool Reset()
        {
            throw new System.NotImplementedException();
        }
    }

其他设备库项目也可以这种方式创建,尽管它们包含的逻辑会有所不同。

现在我们创建使用这些设备的主项目。通过反射,只需在项目引用中添加DeviceCommon就可以使用类库,因为所有设备模型都是从DeviceCommon类库项目中的IDevice接口扩展而来的。这是反射的力量:使用接口,我们可以找到从它扩展的所有类对象,并且我们可以访问所有可访问的成员和方法。对于工具,我们将创建App.config配置文件并向其添加DLL引用。它提供了在发布后自动重新构建项目的机会。

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="DllFileName" value="Device1.dll"/>
  </appSettings>
</configuration>

要在主项目中使用的代码片段。这里包含使用反射动态调用App.config显示的每个类库的代码:

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            string path = Environment.CurrentDirectory + @"\";
            var dllFileName = ConfigurationSettings.AppSettings["DllFileName"];

            if (dllFileName == null)
                throw new Exception("Dll file not shown in App.config!");

            string fileForLoad = path + dllFileName;
            if (!File.Exists(fileForLoad))
                throw new Exception("Dll file not found!");

            var myAssembly = Assembly.LoadFile(fileForLoad);
            var serviceType = typeof(IDevice);
            var types = myAssembly.GetTypes().ToList();
            var myServiceType = types.Where(w => 
            serviceType.IsAssignableFrom(w)).ToList().FirstOrDefault();
            if (myServiceType == null)
                throw new Exception("Service not found!");

            var myDevice = Activator.CreateInstance(myServiceType) as IDevice;
            Console.WriteLine("Device model: "+myDevice.GetModel());
            Console.ReadKey();
        }
    }

 

原文地址:https://www.codeproject.com/Tips/5160372/Using-Reflections-in-Csharp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值