必经之路,.NET简谈——跨进高级编程门槛的必经之路

我们继续C#基础知识的学习,这篇文章对前面基础知识学习的朋友有着举足轻重的作用;为了延续基础知识学习的热情,我编写了这篇特殊的文章。
本篇文章的中心是想借“.NET简谈反射(动态调用)”一文继续发挥下去,让朋友能一气呵成,到底反射能用在什么地方,究竟能起到多么高级的作用。
下面我就拿具体的例子讲解,不废话了请随我来;
1:必须具备的基础知识
C#接口:要想用反射进行高深的使用,必须先具备接口方面的基础,只有用接口了才能是系统真真的活起来。参考.NET简谈接口 一文;
C#委托、事件:在动态调用的过程中,我们难免要进行一些数据的传递,这样的传递是要用接口进行传递,我们不可能强耦合。参考.NET简谈事件与委托一文;
C#反射:这是最关键的一点,所有的东西都是围绕这个点在转,在我们下面的示例中,我们要动态的使用反射获取接口对象。参考.NET简谈反射(动态调用) 一文;
2:示例内容介绍
示例的主要内容是围绕着我们前面所学习的基础知识的做统一应用,以巩固我们的基础,使我们能在真正的项目中灵活运用,将自己提升到一个新的高度;
都知道接口是规范,都知道事件委托,都知道反射,但是我们都只是知道这些零零散散的知识点,我们怎么将这些小技术穿起来,形成坚实的代码结构;
示例要进行讲解的大概内容是这样的:我们定义一个接口,然后用对象去实现它,在我们使用的时候,我们动态的通过反射的去调用,但是反射的时候,我需要用接口进行确定唯一性,因为我们更本不知道谁实现了接口,所以接口的好处就出来了;
3:开始示例学习
定义接口:
using System; using System.Collections.Generic; using System.Text; namespace MainInterface { /// /// 成功计算后的委托 /// /// 返回计算后的值
public delegate void AddHandler(int count); /// /// 添加方法接口 /// public interface AddInterface { /// /// 计算结束后的事件 /// event AddHandler AddEndEvent; /// /// 计算两个数的和 /// /// number1
/// number2
void add(int i, int j); } }

实现接口:
using System; using System.Collections.Generic; using System.Text; namespace TestDll { public class Math : MainInterface.AddInterface { #region AddInterface 成员 public event MainInterface.AddHandler AddEndEvent; public void add(int i, int j) { AddEndEvent(i + j); } #endregion } }
具体调用:
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Diagnostics; namespace Reflection { class Program { static void Main(string[] args) { Assembly dll = Assembly.LoadFile(Environment.CurrentDirectory + "\\TestDll.dll"); foreach (Type type in dll.GetTypes()) { if (type.GetInterface("MainInterface.AddInterface") != null) { MainInterface.AddInterface add = Activator.CreateInstance(type, true) as MainInterface.AddInterface; add.AddEndEvent += new MainInterface.AddHandler(add_AddEndEvent); add.add(10, 20); } } } static void add_AddEndEvent(int count) { Console.WriteLine("Invoke Method:\n" + count.ToString()); Console.ReadLine(); } } }
总结:所谓麻雀虽小,五脏俱全;上面的示例代码虽然没什么作用,但是基本上能概括我们日常所用到的;这也是我们进入框架开发、系统开发必经之路;
Tags:  登门槛效应 门槛石 必经之路英文 人生必经之路 必经之路

延伸阅读

最新评论

发表评论