简体   繁体   English

从子元素引用父元素的值

[英]Referencing a parent's value from a child element

I am trying to figure out a more elegant way to set the property of a parent in c#. 我试图找出一种更优雅的方式来设置c#中父项的属性。 I currently pass the parent into the child element, and reference it that way. 我目前将父元素传递给子元素,并以这种方式引用它。 This seems both cumbersome and possibly even incorrect. 这看起来既麻烦又可能不正确。

The Child: 孩子:

 public class ValidatedField<T>
    {
        public OpenIssues parent { get; set; } 
        //Other values
        public void Highlight()
        {
            parent.isNotValid = true;
            isHighlighted = true;
        }
    }

And the Parent: 和父母:

public class OpenIssues
{
    public OpenIssues()
    {
        DateAppealFiled = new ValidatedField<DateTime?>(this);
    }
    public bool isNotValid { get; set; }
    public ValidatedField<DateTime?> DateAppealFiled { get; set; }
}

Is there a more streamlined way to reference the parent in this case? 在这种情况下,是否有更简化的方式来引用父级? Or am I doomed to sending the entire parent to the child, just to modify one value in the parent? 或者我注定要将整个父母发送给孩子,只是为了修改父母中的一个值?

Is there a more streamlined way to reference the parent in this case? 在这种情况下,是否有更简化的方式来引用父级? Or am I doomed to sending the entire parent to the child, just to modify one value in the parent? 或者我注定要将整个父母发送给孩子,只是为了修改父母中的一个值?

The entire parent (in your words) is just a few bytes of reference/pointer 整个父(用你的话说)只是几个字节的引用/指针

However, 然而,

You can essentially do this one of 3 ways 你基本上可以通过3种方式之一做到这一点

  1. Pass in a concrete reference or interface from your parent. 传递父母的具体参考或界面。
  2. Use events/delegate/action and register then trigger them on update 使用events / delegate / action并注册然后在更新时触发它们
  3. Or a decoupled pub/sub messaging system or mediator 或者是一个解耦的发布/订阅消息系统或中介

What you are doing is fine, though all have their downsides and are cumbersome in different ways 你正在做的事情很好,虽然都有它们的缺点并且在不同的方面很麻烦

The most modern approach is a decoupled messaging system, this is common in viewmodels where you don't want to couple view models and classes together. 最现代的方法是分离的消息传递系统,这在视图模型中很常见,您不希望将视图模型和类耦合在一起。 However, this is most likely overkill for trivial situations. 然而,对于琐碎的情况来说,这很可能是过度杀伤力。

Also too, actions and events have their places as well. 同样,行动和事件也有其自己的位置。 The parent(or someone) subscribes, and unsubscribes (well... should). 父母(或某人)订阅,取消订阅(嗯......应该)。

However, if you don't mind the tight coupling of your parent and child, and if there is little need to use them in different parent child configuration, just use references. 但是,如果您不介意父和子的紧密耦合,并且如果几乎不需要在不同的父子配置中使用它们,则只需使用引用。 No harm done. 没有伤害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM