前田稔(Maeda Minoru)の超初心者のプログラム入門
![]()
![]()
/***********************************************/
/*★ プロキシで複数メソッドを定義 前田 稔 ★*/
/***********************************************/
using System;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Reflection;
|
public class MyMethod : MarshalByRefObject
{
public void Print(string s)
{ Console.WriteLine(s);
}
public int Add(int a, int b)
{ Console.WriteLine("Add() が実行されました");
return a + b;
}
}
|
public class MyProxyClass : RealProxy
{
private Object myObject = null;
private Type myType = null;
// コンストラクタから RealProxy のコンストラクタを呼び出す
public MyProxyClass(Type argType) : base(argType)
{ myType = argType;
myObject = Activator.CreateInstance(argType);
}
// Invoke() をオーバライドして Method を呼び出す
public override IMessage Invoke(IMessage imsg)
{ IMethodMessage call = (IMethodMessage)imsg;
Console.WriteLine(call.MethodName + "を呼び出します");
Object obj = myType.InvokeMember(call.MethodName,
BindingFlags.InvokeMethod, null, myObject, call.Args );
ReturnMessage res = new ReturnMessage(obj, null, 0,
((IMethodCallMessage)imsg).LogicalCallContext,
(IMethodCallMessage)imsg );
return res;
}
}
|
class MainClass
{
[STAThread]
static void Main()
{
// 透過プロキシを生成する
MyProxyClass mycls = new MyProxyClass(typeof(MyMethod));
MyMethod sample = mycls.GetTransparentProxy() as MyMethod;
// 透過プロキシからメソッドを呼び出す
sample.Print("あいうえお");
int val = sample.Add(10,20);
Console.WriteLine(val.ToString());
Console.ReadLine();
}
}
|
![]()