c#中怎么通过自定义Attribute获取接口

c#中怎么通过自定义Attribute获取接口

今天就跟大家聊聊有关c#中怎么通过自定义Attribute获取接口,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一般的接口实现多态

定义接口

interface Ipeople {  void say(); }

定义实现的类

public class man : Ipeople {  public void say()  {   MessageBox.Show("man");  } } public class woman : Ipeople {  public void say()  {   MessageBox.Show("woman");  } }

一般实现的方法

升级版

添加自定义(这个网上好多)

实现类

调用方法

private static void NewMethod(string tpye)  {   Ipeople ib = null;   var types = AppDomain.CurrentDomain.GetAssemblies()      .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(Ipeople))))      .ToArray();   foreach (var v in types)   {    var attribute = v.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault();    if (attribute != null && ((NameAttribute)attribute).Name == tpye)    {     ib = (Ipeople)v.Assembly.CreateInstance(v.FullName);     break;    }   }   if (ib != null) ib.say();  }

这个可以避免需要维护swich语句

看完上述内容,你们对c#中怎么通过自定义Attribute获取接口有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。