gpt4 book ai didi

c# - 如何使用即兴接口(interface)访问代理对象

转载 作者:行者123 更新时间:2023-11-30 20:20:31 26 4
gpt4 key购买 nike

使用 impromptu-interface 时如何访问 Duck Typed 代理对象.考虑我的示例代码,当我尝试将我的 Duck Typed Object 转换为代理对象时,我得到一个 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());
}
}
}

异常情况如下:

An unhandled exception of type 'System.InvalidCastException' occurred in ConsoleApplication1.exe

Additional information: Unable to cast object of type 'ActLike_IPondBird_c7dd53902ec74f01a3844d4789244ea3' to type 'ConsoleApplication1.Duck'.

最佳答案

你不能。你可以考虑行

IPondBird myInterface = Impromptu.ActLike(thing);

好像是

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

话虽如此,您可以将对 native 对象的引用作为契约(Contract)本身的一部分——例如:

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;

关于c# - 如何使用即兴接口(interface)访问代理对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36400395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com