【问题标题】:In what cases the GetType() method would return type of an interface在什么情况下 GetType() 方法会返回接口的类型
【发布时间】:2014-09-29 11:02:07
【问题描述】:

我问这个是因为我得到了一个由 WCF 运行时生成的对象,并且在它上面调用 GetType() 会返回接口的类型。因此,如果您对 WCF 不熟悉或不感兴趣,这是一个更具体的问题。

这是我问的相关问题: why an object of WCF service contract interface can be casted to IClientChannel

【问题讨论】:

  • 对此一无所知,但这可能有帮助吗? social.msdn.microsoft.com/Forums/en-US/…
  • 感谢@RenniePet,虽然我还没有准备好理解那篇代码项目文章,但它让我无法一直思考底层模型。

标签: c#


【解决方案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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2020-11-04
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2021-08-28
    相关资源
    最近更新 更多