欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#自定义Attribute获取接口实现示例代码

程序员文章站 2023-12-30 23:31:28
一般的接口实现多态 定义接口 interface ipeople { void say(); } 定义实现的类 public class...

一般的接口实现多态

定义接口

 interface ipeople
 {
  void say();
 }

定义实现的类

 public class man : ipeople
 {
  public void say()
  {
   messagebox.show("man");
  }
 }

 public class woman : ipeople
 {
  public void say()
  {
   messagebox.show("woman");
  }
 }

一般实现的方法

c#自定义Attribute获取接口实现示例代码

升级版

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

c#自定义Attribute获取接口实现示例代码

实现类

c#自定义Attribute获取接口实现示例代码

调用方法

 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语句

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。

上一篇:

下一篇: