如何在DynamicProxy中为C#Auto-Property提供默认值?

时间:2014-03-19 09:42:34

标签: c# castle castle-dynamicproxy dynamic-proxy

namespace ConsoleApplication15
{
  using System;
  using Castle.DynamicProxy;

  public class Test
  {
    private SubTestClass subTestClass;

    public string Status
    {
      get
      {
        return this.subTestClass.SubStatus;
      }

      set
      {
        this.subTestClass.SubStatus = value;
      }
    }

    public int Data { get; set; }
  }

  public class SubTestClass
  {
    public string SubStatus { get; set; }
  }

  public class Program
  {
    public static void Main(string[] args)
    {
      var proxyGenerator = new ProxyGenerator();
      var testObject = proxyGenerator.CreateClassProxy<Test>();
      if (testObject.Status != null)
      {
        Console.WriteLine("Working");
      }
    }
  }
}

我有以下代码,我想将Status默认值设置为Empty字符串。 当我运行以下代码时,Status字符串始终为Null并抛出一个空异常!!

testObject.Status 这将返回一个空字符串而不会抛出异常。

2 个答案:

答案 0 :(得分:2)

要为自动实现的属性提供默认值,您必须在构造函数中执行以下操作:

[TestFixture]
public class UnitTest1
{
    [Test]
    public void TestMethod1()
    {
        var proxyGenerator = new ProxyGenerator();
        var testObject = proxyGenerator.CreateClassProxy<Test>();
        Console.WriteLine(
            testObject.Status != null 
            ? "Working" 
            : "no....");
    }
}

public class Test
{
    private SubTestClass subTestClass = new SubTestClass();

    public string Status
    {
        get
        {
            return this.subTestClass.SubStatus;
        }

        set
        {
            this.subTestClass.SubStatus = value;
        }
    }

    public int Data { get; set; }
}

public class SubTestClass
{
    public SubTestClass()
    {
        SubStatus = "";
    }
    public string SubStatus { get; set; }
}

答案 1 :(得分:0)

我找到了IInterceptor问题的解决方案我可以创建我的自定义结果。 谢谢你的帮助!

namespace ConsoleApplication15
{
  using System;
  using Castle.DynamicProxy;

  public class Test
  {
    private SubTestClass subTestClass;

    public virtual string Status
    {
      get
      {
        return this.subTestClass.SubStatus;
      }

      set
      {
        this.subTestClass.SubStatus = value;
      }
    }

    public int Data { get; set; }
  }

  public class SubTestClass
  {
    public string SubStatus { get; set; }
  }

  public class Program
  {
    public static void Main(string[] args)
    {
      var proxyGenerator = new ProxyGenerator();

      var testObject = proxyGenerator.CreateClassProxy<Test>(new MyInter());


      if (testObject.Status != null)
      {
        Console.WriteLine("Working");
      }
    }

  }

  public class MyInter : IInterceptor
  {
    public void Intercept(IInvocation invocation)
    {
      if (invocation.Method.ReturnType == typeof(string))
      {
        invocation.ReturnValue = string.Empty;
      }
    }
  }
}