使用即兴接口时,如何访问Duck Typed代理对象。考虑一下我的代码,它说明了我的例子,当我试图将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());
}
}
}
例外情况如下:
发生"System.InvalidCastException"类型的未经处理的异常在ConsoleApplication1.exe 中
附加信息:无法强制转换类型为的对象类型为"ActLike_IPondBird_c7dd53902ec74f01a3844d4789244ea3"'控制台应用程序1.Duck'.
你不能。你可以考虑一下
IPondBird myInterface = Impromptu.ActLike(thing);
像
public class Wrapper : IPondBird
{
public Wrapper(Duck duck) { ... }
}
IPondBird myInterface = new Wrapper(thing);
也就是说,您可以将对本机对象的引用作为合同本身的一部分,比如:
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;
当您使用即兴接口时,生成的代理始终具有IActLikeProxy
的显式接口实现。
IPondBird myInterface = Impromptu.ActLike(thing);
var duck = (Duck)((IActLikeProxy)myInterface).Original;