软件编程
位置:首页>> 软件编程>> C#编程>> c#自定义Attribute获取接口实现示例代码

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

作者:麦叶  发布时间:2022-09-02 05:05:26 

标签: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");
 }
}

一般实现的方法

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

来源:https://www.maiyewang.com/2019/09/18/c自定义attribute获取接口实现-2/

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com