当前位置: 移动技术网 > IT编程>开发语言>c# > c#自定义Attribute获取接口实现示例代码

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

2020年03月09日  | 移动技术网IT编程  | 我要评论

一般的接口实现多态

定义接口

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

总结

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网