获取代理对象的基础类型

Had*_*ari 14 c# reflection proxy castle-dynamicproxy

我正在使用Castle DynamicProxy,我的ViewModel是一个代理,如下所示:

namespace MyApplication.ViewModels
{
   public class MyViewModel : BaseViewModel, IMyViewModel
   {
   }
}

我的viewmodel的代理看起来像这样:

{Name ="IRootViewModelProxyffecb133f590422098ca7c0ac13b8f98"FullName ="IRootViewModelProxyffecb133f590422098ca7c0ac13b8f98"}

我想获得被代理的实际类型的实际类型或命名空间.有没有办法做到这一点?我想要一些返回MyApplication.ViewModels.MyViewModel类型的东西.如果我使用concreate类作为代理,BaseType将返回正在代理的实际类,但在使用该接口时,BaseType将返回System.Object.

Had*_*ari 16

您似乎可以执行以下操作来获取实际类型:

(proxy As IProxyTargetAccessor).DynProxyGetTarget().GetType()


Gre*_*vec 8

如果您代理的是类而不是接口,则可以获取如下的基础类型:

var unproxiedType = ProxyUtil.GetUnproxiedType(proxy);
Run Code Online (Sandbox Code Playgroud)

如果您无法访问ProxyUtil,这也将起作用:

private static Type GetUnproxiedType(object source)
{
   var proxy = (source as IProxyTargetAccessor);

   if (proxy == null)
     return source.GetType();

   return proxy.GetType().BaseType;            
}
Run Code Online (Sandbox Code Playgroud)

  • BTW我认为`ProxyUtil`在DP本身可能是一个有用的东西,所以我将它从Windsor移植到DynamicProxy用于下一个版本. (2认同)