1.首先引用dllCastal.Core.dll
2.
public interface IStorageNode { bool IsDead { get; set; } void Save(string message); } public interface IDao { } public class BaseNode : IDao { protected string TestBase() { return "BaseNode"; } } public class StorageNode : BaseNode, IStorageNode { private string _name; public StorageNode(string name) { this._name = name; } public bool IsDead { get; set; } public void Save(string message) { Console.WriteLine(string.Format("\"{0}\" was saved to {1}", message, this._name)); } } public class DualNodeInterceptor : IInterceptor { private IStorageNode _slave; public DualNodeInterceptor(IStorageNode slave) { this._slave = slave; } public void Intercept(IInvocation invocation) { IStorageNode master = invocation.InvocationTarget as IStorageNode; if (master.IsDead) { IChangeProxyTarget cpt = invocation as IChangeProxyTarget; //将被代理对象master更换为slave cpt.ChangeProxyTarget(this._slave); //测试中恢复master的状态,以便看到随后的调用仍然使用master这一效果 master.IsDead = false; } invocation.Proceed(); } } public class CallingLogInterceptor : IInterceptor { private int _indent = 0; private void PreProceed(IInvocation invocation) { if (this._indent > 0) Console.Write(" ".PadRight(this._indent * 4, ' ')); this._indent++; Console.Write("Intercepting: " + invocation.Method.Name + "("); if (invocation.Arguments != null && invocation.Arguments.Length > 0) for (int i = 0; i < invocation.Arguments.Length; i++) { if (i != 0) Console.Write(", "); Console.Write(invocation.Arguments[i] == null ? "null" : invocation.Arguments[i].GetType() == typeof(string) ? "\"" + invocation.Arguments[i].ToString() + "\"" : invocation.Arguments[i].ToString()); } Console.WriteLine(")"); } private void PostProceed(IInvocation invocation) { this._indent--; } public void Intercept(IInvocation invocation) { this.PreProceed(invocation); invocation.Proceed(); this.PostProceed(invocation); } }
3.测试代码
[TestMethod] public void TestMethod1() { ProxyGenerator generator = new ProxyGenerator(); IDao daoInstance =new StorageNode("master"); IStorageNode temp = daoInstance as IStorageNode;//为什么temp不为null IDao node1 = generator.CreateInterfaceProxyWithTarget( daoInstance , new DualNodeInterceptor(new StorageNode("slave")) , new CallingLogInterceptor()); IStorageNode node = node1 as IStorageNode;//为什么node会是null node.Save("my message"); //应该调用master对象 node.IsDead = true; node.Save("my message"); //应该调用slave对象 node.Save("my message"); //应该调用master对象 }
问题是加红的地方。为什么node为null呢。
修改为:
Type[] interfaces = { typeof(IDao), typeof(IStorageNode) };
IDao node1 = (IDao)generator.CreateInterfaceProxyWithTarget(typeof(IDao), interfaces, daoInstance);
IStorageNode node = node1 as IStorageNode;//node不是null,而且和temp相同