我想“装饰”我自己的物品的属性。例如,我想知道一个getter被调用了多少次,设置器需要多长时间,记录任何新值.
我正试图尽可能简单地做到这一点。理想的解决方案可能使用属性,它可以如下所示:
public class MyClass
{
[CountGetterCalls]
[LogSettingValue]
public int SomeProperty;
}我没有成功地实现这个,作为一个解决方案,我尝试了一种属性包装。但这还远远不够完美。你会怎么做?
public class MyClass
{
public MyClass()
{
SomeProperty = new PropertyWrapper<int>(new CountCallsPropertyDecorator<int>(new LogSettingPropertyDecorator<int>(new NullDecorator<int>())));
}
public PropertyWrapper<int> SomeProperty;
}
public interface IPropertyDecorator<T>
{
void OnGetValue();
void OnSetValue(T value);
}
public class PropertyWrapper<T>
{
private readonly IPropertyDecorator<T> _decorator;
private T _value;
public PropertyWrapper(IPropertyDecorator<T> decorator)
{
_decorator = decorator;
}
public T Value
{
get
{
_decorator.OnGetValue();
return _value;
}
set
{
_decorator.OnSetValue(value);
_value = value;
}
}
}
public class CountCallsPropertyDecorator<T> : IPropertyDecorator<T>
{
private readonly IPropertyDecorator<T> _decorator;
private int _nbGetCalled;
private int _nbSetCalled;
public int NbGetCalled { get { return _nbGetCalled; } }
public int NbSetCalled { get { return _nbSetCalled; } }
public CountCallsPropertyDecorator(IPropertyDecorator<T> decorator)
{
_decorator = decorator;
}
public void OnGetValue()
{
_decorator.OnGetValue();
_nbGetCalled++;
}
public void OnSetValue(T value)
{
_decorator.OnSetValue(value);
_nbSetCalled++;
}
}
public class LogSettingPropertyDecorator<T> : IPropertyDecorator<T>
{
private readonly IPropertyDecorator<T> _decorator;
public LogSettingPropertyDecorator(IPropertyDecorator<T> decorator)
{
_decorator = decorator;
}
public void OnGetValue() { _decorator.OnGetValue(); }
public void OnSetValue(T value)
{
_decorator.OnSetValue(value);
Console.WriteLine("Property called.");
}
}
public class NullDecorator<T> : IPropertyDecorator<T>
{
public void OnGetValue() { }
public void OnSetValue(T value) { }
}发布于 2014-06-26 12:24:24
在.net中,方法“修饰”不像其他语言(例如Python)那样工作,属性的存在不会改变方法的行为,只改变它的元数据。元数据可用于通过其他工具更改其行为。
您需要和AOP框架(如专有的PostSharp)或动态代理生成器(如LinFu或卡塞尔)来实现您想要的目标。
两者各有优缺点,各看一看。
https://stackoverflow.com/questions/24430261
复制相似问题