Firing an event / function on a property? (C#)

后端 未结 8 1473
你的背包
你的背包 2021-02-08 11:46

I am using a class that I cannot edit, it has a property (a boolean) of which it would be nice to be informed when it changes, I can\'t edit the properties get or set as I am im

相关标签:
8条回答
  • 2021-02-08 12:45

    You will need to create a class that wraps the class in the dll, within the setter property just raise an event there using the normal methods.

    0 讨论(0)
  • 2021-02-08 12:46

    I think Alex' idea of a wrapper is good, however, given that the most important thing to you is that you know that the value is changed before use, you could simply move the notification to the getter, circumventing the worries of internal value change. That way you get something similar to polling, yet reliable:

    class MyClass : BaseClass
    {
        //local value
        private bool local;
    
        //first access yet?
        private bool accessed = false;
    
        // Override base property.
        public new bool MyProperty
        {
            get
            {
                if(!accessed)
                {
                    // modify first-get case according to your taste, e.g.
                    local = base.MyProperty;
                    accessed = true;
                    RaiseMyPropertyChangedBeforeUseEvent();
                }
                else
                {
                    if(local != base.MyProperty)
                    {
                        local = base.MyProperty;
                        RaiseMyPropertyChangedBeforeUseEvent();
                    }
                }
    
                return local;
            }
    
            set
            {
                base.MyProperty = value;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题