一般的接口实现多态
定义接口
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语句
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。
原文链接:https://www.maiyewang.com/2019/09/18/c自定义attribute获取接口实现-2/