c# - 从现有对象创建代理

标签 c# castle-dynamicproxy

使用 CaSTLe.DynamicProxy,从现有类实例创建代理的最佳方法是什么?

// The actual object
Person steve = new Person() { Name = "Steve" };

// Create a proxy of the object
Person fakeSteve = _proxyGenerator.CreateClassProxyWithTarget<Person>(steve, interceptor)

// fakeSteve now has steve as target, but its properties are still null...

这是 Person 类:

public class Person
{
    public virtual string Name { get; set; }
}

这是拦截器类:

public class PersonInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {   
        Person p = invocation.InvocationTarget as Person;

        if (invocation.Method.Name.Equals(get_Name)
        {
            LoadName(p);
        }
    }

    private void LoadName(Person p)
    {
        if (string.IsNullOrEmpty(p.Name))
        {
            p.Name = "FakeSteve";
        }
    }
}

最佳答案

如果您的 Person 类只有非虚拟属性,则代理无法访问它们。尝试使属性虚拟化。

http://kozmic.net/2009/02/23/castle-dynamic-proxy-tutorial-part-vi-handling-non-virtual-methods/

关于c# - 从现有对象创建代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20703788/

相关文章:

c# - 拦截 Controller

c# - Microsoft 安全更新 MS13-004 后在 MSTest 中执行单元测试时出现 System.InvalidProgramException

c# - White UI Automation库如何使用CaSTLe DynamicProxy?

c# - 垃圾收集器不会收集使用创建的对象

c# - StreamSocket下DataWriter的StoreAsync是如何工作的?

c# - 我应该在哪里保存应用程序数据?

asynchronous - 是否可以使用 CaSTLe.DynamicProxy 创建异步拦截器?

c# - 使用 WPF 客户端和 Active Directory ADFS 对 Cloud NodeJS 后端进行身份验证

c# - 如何使用反射调用泛型类型内的非泛型方法

unit-testing - 如何对拦截器进行单元测试?