你需要构建一个调用站点,创建一个绑定器等操作。最简单的方法是编译这个代码:
public static object GetDynamicValue(dynamic o, string name)
{
return o.Foo;
}
然后使用 Reflector 进行反编译并弄清楚它在干什么。不过要注意,这会相当复杂,而且你需要将其从单个、静态、缓存的调用站点更改为每次调用都创建一个新的站点。
以下是一个能够工作的示例... 但是否完全正确则是另一回事 :) (我通过完全按照上述建议所做来实现了这一点。)
using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Dynamic;
using System.Runtime.CompilerServices;
class Test
{
public static object GetDynamicValue(dynamic o, string name)
{
CallSite<Func<CallSite, object, object>> site
= CallSite<Func<CallSite, object, object>>.Create
(Binder.GetMember(CSharpBinderFlags.None, name,
typeof(Test), new CSharpArgumentInfo[]
{ CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
return site.Target(site, o);
}
static void Main()
{
Console.WriteLine(GetDynamicValue("hello", "Length"));
}
}