VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • c#自定义Attribute获取接口实现示例代码

一般的接口实现多态

定义接口

?
1
2
3
4
interface Ipeople
{
 void say();
}

定义实现的类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class man : Ipeople
{
 public void say()
 {
  MessageBox.Show("man");
 }
}
 
public class woman : Ipeople
{
 public void say()
 {
  MessageBox.Show("woman");
 }
}

一般实现的方法

升级版

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

实现类

调用方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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语句


相关教程