简体   繁体   English

如何使用即兴接口访问代理对象

[英]How to access proxied object using impromptu-interface

How can I get access to the Duck Typed proxied object when using impromptu-interface . 使用impromptu-interface时,如何访问Duck Typed代理对象。 consider my code that illustrates my example where I get a InvalidCastException when I try to cast my Duck Typed Object to the proxied Object: 考虑一下说明我的示例的代码,当我尝试将Duck Typed对象转换为代理对象时,我得到一个InvalidCastException

using System;
using ImpromptuInterface;

namespace ConsoleApplication1
{
    public class Duck
    {
        public string Says { get; set; }

        public int GetNumberOfQuacksPerMinute()
        {
            return 42;
        }
    }

    public interface IPondBird
    {
        string Says { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Duck says Quack! Quack!! Quack!!!
            var thing = new Duck { Says = "Quack! Quack!! Quack!!!" };

            IPondBird myInterface = Impromptu.ActLike(thing);

            // ...

            // Later on, I want to get access to a proxied object, but I 
            // get a InvalidCastException here
            Duck proxiedObject = (Duck) myInterface;
            Console.WriteLine("Duck # quacks per minute: " 
                + proxiedObject.GetNumberOfQuacksPerMinute());
        }
    }
}

Exception is as follows: 异常如下:

An unhandled exception of type 'System.InvalidCastException' occurred in ConsoleApplication1.exe ConsoleApplication1.exe中发生类型为'System.InvalidCastException'的未处理异常

Additional information: Unable to cast object of type 'ActLike_IPondBird_c7dd53902ec74f01a3844d4789244ea3' to type 'ConsoleApplication1.Duck'. 附加信息:无法将类型为“ ActLike_IPondBird_c7dd53902ec74f01a3844d4789244ea3”的对象强制转换为“ ConsoleApplication1.Duck”类型。

You can't. 你不能 You can think about line 你可以考虑线

IPondBird myInterface = Impromptu.ActLike(thing);

As something like 就像

public class Wrapper : IPondBird 
{
  public Wrapper(Duck duck) { ... }
}
IPondBird myInterface = new Wrapper(thing);

That being said you can make the reference to native object part of the contract itself - like: 话虽如此,您可以将本地对象的引用作为合同本身的一部分,例如:

public interface IPondBird
{
    string Says { get; set; }
    object NativeObject { get; }
}

public class Duck
{
    public string Says { get; set; }

    public int GetNumberOfQuacksPerMinute()
    {
        return 42;
    }

    public object NativeObject { get { return this; } }
}

IPondBird myInterface = Impromptu.ActLike(thing);   
var duck = (Duck)myInterface.NativeObject;

When you use impromptu interface, the generated proxy always has an explicit interface implementation for IActLikeProxy . 使用即兴接口时,生成的代理始终具有IActLikeProxy的显式接口实现。

IPondBird myInterface = Impromptu.ActLike(thing);   
var duck = (Duck)((IActLikeProxy)myInterface).Original;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM