一般的接口实现多态

定义接口

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
    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获取接口实现 随笔 第1张

升级版

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

c#自定义Attribute获取接口实现 随笔 第2张

实现类

c#自定义Attribute获取接口实现 随笔 第3张c#自定义Attribute获取接口实现 随笔 第4张

调用方法

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

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄