一般的接口实现多态

定义接口

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

总结

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。