C#,用于处理依赖属性的更改和更新的简化代码
显然,我不是 C# 专家。我想通过使用匿名处理程序或 lambda 来简化此代码,但不确定。 ValueHasChanged
是在 dp 更改时使用的 PropertyChangedCallback
,它确保将监视新对象的更新,以便使用相同的代码处理更改和更新: 处理新值
。遗憾的是,创建第二个处理程序 ValueHasBeenUpdated
仅用于调用相同的方法。是否有可能删除 ValueHasBeenUpdated
的定义?谢谢。
private static void ValueHasChanged(
DependencyObject sender, DependencyPropertyChangedEventArgs args) {
// get instance
MyClass1 instance = sender as MyClass1;
// unregister on old object
if (args.OldValue != null) (args.OldValue as MyClass2).PropertyChanged -=
instance.ValueHasBeenUpdated;
// register for updates on new object
if (args.NewValue != null) (args.NewValue as MyClass2).PropertyChanged +=
instance.ValueHasBeenUpdated;
// process new value anyway
instance.ProcessNewValue();
}
// value has been updated
private void ValueHasBeenUpdated(object sender, PropertyChangedEventArgs e) {
// just call the actual method that will process it, not elegant...
ProcessNewValue();
}
// process any new or updated object
private void ProcessNewValue() {...}
Obviously, I'm not an expert in C#. I would like to simplify this code by using an anonymous handler, or maybe a lambda, not sure. ValueHasChanged
is a PropertyChangedCallback
used when a dp is changed, it ensures the new object will be monitored for update, so that both changes and updates will be processed using the same code: ProcessNewValue
. The pity here is to create a second handler ValueHasBeenUpdated
only to call the same method. Is there a possibility to remove the definition of ValueHasBeenUpdated
? Thanks.
private static void ValueHasChanged(
DependencyObject sender, DependencyPropertyChangedEventArgs args) {
// get instance
MyClass1 instance = sender as MyClass1;
// unregister on old object
if (args.OldValue != null) (args.OldValue as MyClass2).PropertyChanged -=
instance.ValueHasBeenUpdated;
// register for updates on new object
if (args.NewValue != null) (args.NewValue as MyClass2).PropertyChanged +=
instance.ValueHasBeenUpdated;
// process new value anyway
instance.ProcessNewValue();
}
// value has been updated
private void ValueHasBeenUpdated(object sender, PropertyChangedEventArgs e) {
// just call the actual method that will process it, not elegant...
ProcessNewValue();
}
// process any new or updated object
private void ProcessNewValue() {...}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
做你所做的事并没有什么错。它可能看起来“不优雅”,但它是可读的。可读性比优雅更重要。可能还有其他解决方案,但对于其他编码人员来说(或者您在 6 个月后才能理解),它们都会更加令人困惑。
坚持你所拥有的。
Nothing wrong with doing what you've done. It may seem "inelegant," but it is readable. Readability is more important than elegance. There may be other solutions, but they will all be more confusing for other coders to understand (or for you to understand 6 months from now).
Stick with what you've got.