Getのために簡単に拡張できるSetのインターセプタをもう一週間書きました。RealProxyを使用しています。つまり、基本クラスがMarshalByRefObjectを派生させる必要があります。
また、クラスを抽象化し、Reflection Emitを使用して、すべてのプロパティをラップする具体的なクラスを構築することもできます。
また、あなたはこのまたはPostSharpを回避するために、コードジェネレータで見ることができる...このソリューションの
パフォーマンスが恒星ではありませんが、それが結合最もUIのために十分高速である必要があります。これは、プロキシ呼び出しのためのLCGメソッドを生成することによって改善することができます。
public interface IInterceptorNotifiable {
void OnPropertyChanged(string propertyName);
}
/// <summary>
/// A simple RealProxy based property interceptor
/// Will call OnPropertyChanged whenever and property on the child object is changed
/// </summary>
public class Interceptor<T> where T : MarshalByRefObject, IInterceptorNotifiable, new() {
class InterceptorProxy : RealProxy {
T proxy;
T target;
EventHandler<PropertyChangedEventArgs> OnPropertyChanged;
public InterceptorProxy(T target)
: base(typeof(T)) {
this.target = target;
}
public override object GetTransparentProxy() {
proxy = (T)base.GetTransparentProxy();
return proxy;
}
public override IMessage Invoke(IMessage msg) {
IMethodCallMessage call = msg as IMethodCallMessage;
if (call != null) {
var result = InvokeMethod(call);
if (call.MethodName.StartsWith("set_")) {
string propName = call.MethodName.Substring(4);
target.OnPropertyChanged(propName);
}
return result;
} else {
throw new NotSupportedException();
}
}
IMethodReturnMessage InvokeMethod(IMethodCallMessage callMsg) {
return RemotingServices.ExecuteMessage(target, callMsg);
}
}
public static T Create() {
var interceptor = new InterceptorProxy(new T());
return (T)interceptor.GetTransparentProxy();
}
private Interceptor() {
}
}
使用法:あなたの要求の
class Foo : MarshalByRefObject, IInterceptorNotifiable {
public int PublicProp { get; set; }
public string lastPropertyChanged;
public void OnPropertyChanged(string propertyName) {
lastPropertyChanged = propertyName;
}
}
[Test]
public void TestPropertyInterception() {
var foo = Interceptor<Foo>.Create();
foo.PublicProp = 100;
Assert.AreEqual("PublicProp", foo.lastPropertyChanged);
}
}
ええ、私はいくつかあるので、すべてのプロパティにチェックを追加するのを避けようとしています、そして、コードはそれぞれほぼ同じです。 –