我正在尝试动态生成方法包装器。为了概念验证,我希望有一个什么都不做的包装器。代码看起来像这样:
cSomeClassName testObject = new cSomeClassName();
dynamic wrapperObject = new ExpandoObject() as IDictionary<string, Object>;
foreach (var method in typeof(cSomeClassName).GetMethods())
{
wrapperObject.Add(method.Name,
(method.GetParameters()) => testObject.CallMethodWithParams(method.Name, method.GetParameters()));
}
拨打电话
testObject.MethodName(params);
现在可以等同于
wrapperObject.MethodName(params);
我意识到这是一个非常破碎的示例实现,但我不确定如何改进它。
答案 0 :(得分:0)
经过多次陪审团操纵,我给你解决方案:
class cMethodExecutor
{
private ArrayList m_ArgumentList;
private Object m_CallObject;
private string m_MethodName;
public cMethodExecutor(Object iObject)
{
m_CallObject = iObject;
m_ArgumentList = new ArrayList();
m_MethodName = "";
}
public void SetMethodName(string iMethodName)
{
m_MethodName = iMethodName;
}
public void AddArgument(Object iArgument)
{
m_ArgumentList.Add(iArgument);
}
public object Execute()
{
return m_CallObject.GetType().GetMethod(m_MethodName).Invoke(m_CallObject, m_ArgumentList.ToArray());
}
}
public delegate object ParamsFunc(params object[] iArgs);
//For now, we're going to just fall through to the original object:
IDictionary<string, object> obj = new ExpandoObject();
foreach (var method in typeof(cTestTarget).GetMethods())
{
Console.WriteLine("Adding method: " + method.Name + "\n");
obj.Add(method.Name, new ParamsFunc( inputList =>
{
cMethodExecutor newExecutor = new cMethodExecutor(iTestTarget);
newExecutor.SetMethodName(method.Name);
foreach (var param in inputList)
{
newExecutor.AddArgument(param);
}
return newExecutor.Execute();
}));
}
iTestTarget中存在的任何方法现在都存在于obj中,并发送到原始的iTestTarget。