我正在使用 CaSTLe DynamicProxy 向我的类型添加拦截器。
现在我需要获取底层基本类型(不是代理本身)。
我在 SO 上发现了一些提示,建议像这样使用 ProxyUtil 类:
object realInstance = ProxyUtil.GetUnproxiedInstance(proxyInstance);
这似乎不起作用
bool isProxy = ProxyUtil.IsProxy(realInstance);
永远是真的。
我还尝试使用以下代码片段,这基本上是 ProxyUtil 正在做的:
var accessor = proxyInstance as IProxyTargetAccessor;
var realInstance = accessor.DynProxyGetTarget();
同样的结果, realInstance 仍然是一个代理。
我在这里缺少什么?
最佳答案
这个问题有点老了,但希望我的解决方案(依赖于 .NET 4+)能帮助某人。
创建了一个代理如下:
ProxyGenerator generator = new ProxyGenerator();
MyClass proxy = generator.CreateClassProxyWithTarget(underlying, new MyInterceptor(this));
我已经能够使用以下方法获得基础目标:
internal static TType UnwrapProxy<TType>(TType proxy)
{
if (!ProxyUtil.IsProxy(proxy))
return proxy;
try
{
dynamic dynamicProxy = proxy;
return dynamicProxy.__target;
}
catch (RuntimeBinderException)
{
return proxy;
}
}
它依赖于 CaSTLe 的内部实现——即生成的代理有一个 __target 成员。虽然它很好,而且是自包含的,并通过一两个单元测试进行备份,如果 CaSTLe 的更高版本打破了这一点,我们应该捕获任何变化。这是使用城堡的 v3.2.0.0。
关于.net - 城堡动态代理 : Get unproxied object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11082911/