2014-09-29 25 views
2

我在問這是因爲我得到一個由WCF運行時生成的對象,並且調用它的GetType()返回一個接口的類型。所以如果你對WCF不熟悉或感興趣,這是更具體的問題。在什麼情況下,GetType()方法將返回接口的類型

這是相關的問題,我問: why an object of WCF service contract interface can be casted to IClientChannel

+1

對此不知情,但這樣做可能有幫助嗎? http://social.msdn.microsoft.com/Forums/en-US/1e15e6f7-e187-438d-9a75-27e68bc037cf/objgettype-is-returning-an-interface-definition-rather-than-a-class-definition- is-that?forum = netfxbcl – RenniePet 2014-09-29 02:57:26

+0

Thanks @RenniePet,authough我還沒有準備好理解那個codeproject文章,它阻止我始終考慮底層模型。 – 2014-09-30 01:51:54

回答

1

我不能編目所有情況可能發生的情況,但這裏對這種特殊情況下的一些信息。 CLR有一些工具可以在System.Runtime.Remoting中攔截調用。特別是類RealProxy似乎是特別的。你可以使用它來包裝一個對象並攔截對象上方法的調用。這article有很多關於如何使用/實施RealProxy的細節。我發現你可以用它來攔截GetType之類的方法。我懷疑WCF在動態生成的類下也是這樣做的。示例使用該文章中的一些示例:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine(new DynamicProxy(new Calculator(), typeof(ICalculator)).GetTransparentProxy().GetType()); 
    } 
} 

public interface ICalculator 
{ 
    double Add(double x, double y); 
} 

class Calculator : ICalculator 
{ 
    public double Add(double x, double y) 
    { 
     throw new NotImplementedException(); 
    } 
} 

class DynamicProxy : RealProxy 
{ 
    private readonly object _decorated; 
    private readonly Type _reportedType; 
    private static readonly MethodInfo GetTypeMethodInfo = typeof(object).GetMethod("GetType"); 

    public DynamicProxy(object decorated, Type reportedType) 
     : base(reportedType) 
    { 
     _decorated = decorated; 
     _reportedType = reportedType; 
    } 

    private void Log(string msg, object arg = null) 
    { 
     Console.ForegroundColor = ConsoleColor.Red; 
     Console.WriteLine(msg, arg); 
     Console.ResetColor(); 
    } 

    public override IMessage Invoke(IMessage msg) 
    { 
     var methodCall = msg as IMethodCallMessage; 
     var methodInfo = methodCall.MethodBase as MethodInfo; 
     Log("In Dynamic Proxy - Before executing '{0}'", 
      methodCall.MethodName); 
     try 
     { 
      object result; 
      if (GetTypeMethodInfo.Equals(methodInfo)) 
      { 
       result = _reportedType; 
      } 
      else 
      { 
       result = methodInfo.Invoke(_decorated, methodCall.InArgs); 
      } 

      Log("In Dynamic Proxy - After executing '{0}' ", 
       methodCall.MethodName); 
      return new ReturnMessage(result, null, 0, 
       methodCall.LogicalCallContext, methodCall); 
     } 
     catch (Exception e) 
     { 
      Log(string.Format(
       "In Dynamic Proxy- Exception {0} executing '{1}'", e), 
       methodCall.MethodName); 
      return new ReturnMessage(e, methodCall); 
     } 
    } 
} 
相關問題