Getting underlying type of a proxy object

ぐ巨炮叔叔 提交于 2019-11-30 22:29:44

问题


I'm using Castle DynamicProxy and my ViewModels are a proxy, something like this:

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

a proxy of my viewmodel looks like this though:

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

I want to get the actual type or namespace of the actual type that is being proxied. Is there any way to do this? I want something that returns MyApplication.ViewModels.MyViewModel type. If I'm using concreate class as proxies, BaseType returns the actual class that is being proxied, but when using the interface, BaseType would return System.Object.


回答1:


It seems you can do the following to get the actual type:

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



回答2:


If you are proxying a class and not an interface, you can get the underlying type like this:

var unproxiedType = ProxyUtil.GetUnproxiedType(proxy);

If you don't have access to ProxyUtil this will also work:

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

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

   return proxy.GetType().BaseType;            
}


来源:https://stackoverflow.com/questions/1415675/getting-underlying-type-of-a-proxy-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!