gpt4 book ai didi

c# - 使用 CaSTLe Dynamic Proxy 2 添加额外的接口(interface)?

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

我想为现有类型创建一个动态代理,但要添加一个尚未在目标类型上声明的新接口(interface)的实现。我不知道如何实现这一目标。有任何想法吗?

最佳答案

您可以使用 ProxyGenerator.CreateClassProxy() 的重载有 additionalInterfacesToProxy范围。例如,如果您有一个带有字符串名称属性的类并且想要添加一个 IEnumerable<char>对于枚举名称字符的它,您可以这样做:

public class Foo
{
public virtual string Name { get; protected set; }

public Foo()
{
Name = "Foo";
}
}

class FooInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method == typeof(IEnumerable<char>).GetMethod("GetEnumerator")
|| invocation.Method == typeof(IEnumerable).GetMethod("GetEnumerator"))
invocation.ReturnValue = ((Foo)invocation.Proxy).Name.GetEnumerator();
else
invocation.Proceed();
}
}



var proxy = new ProxyGenerator().CreateClassProxy(
typeof(Foo), new[] { typeof(IEnumerable<char>) }, new FooInterceptor());

Console.WriteLine(((Foo)proxy).Name);
foreach (var c in ((IEnumerable<char>)proxy))
Console.WriteLine(c);

请注意 Name如果您不想代理它,这里的属性不必是虚拟的。

关于c# - 使用 CaSTLe Dynamic Proxy 2 添加额外的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6179970/

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