NVentimiglia / Unity3d-Databinding-Mvvm-Mvc

Unity3d uGUI Observable library for Mvvm / Mvc
http://unity3dfoundation.com
63 stars 16 forks source link

MVVMLight-like Set<T>() Method #3

Closed negue closed 9 years ago

negue commented 9 years ago

The current way to handle viewmodel properties is like this:

private bool _isVisible;
public bool IsVisible
{
   get { return _isVisible; }
   set
   {
      if (_isVisible == value)
         return;
      _isVisible = value;
      NotifyProperty("IsVisible", value);
      enabled = value;
   }
}

it works sure, but I dont like that style, I'm kinda used to the CallerMemberNameAttribute and MVVMLight Set-Method.

Too bad this attribute doesn't exist...

Anyway what do you think of this example code:

private bool _isVisible;
public bool IsVisible
{
   get { return _isVisible; }
   set
   {
      if(Set(ref _isVisible, value))
         enabled = value;
   }
}

Set-Method in Unity

      protected bool Set<T>(ref T valueHolder, T value, string propName = null)
      {
         var same = EqualityComparer<T>.Default.Equals(valueHolder, value);

         if(!same)
         {
            var stackTrace = new StackTrace();           // get call stack
            var stackFrames = stackTrace.GetFrames().ToList();  // get method calls (frames)

            if(propName == null && stackFrames.Count > 1)
            { 
               propName = stackFrames[1].GetMethod().Name.Replace("set_", "");
            }

            valueHolder = value;

            NotifyProperty(propName, value);

            return true;
         }

         return false;
      }
NVentimiglia commented 9 years ago

Ill experiment with this shortly.

My only concern is the use of reflection which is relatively expensive and may cause some cross platform issues (most notably IOS and Webplayer). That said, it is cleaner if it works.

NVentimiglia commented 9 years ago

This has been added. Also I was wrong about the reflection. This method is faster for some reason. I have included a second example scene which demonstrates this.

NVentimiglia commented 9 years ago

Correction : the removal of the second equity check (line 37) makes the new method (Set) significantly slower. (.07:4.0)

negue commented 9 years ago

Hm I see,

maybe then a Set-Method without the Stacktraces, then we'd have to write the current Property down BUT we dont have to check, set and raise propertychanged event for each property, which should be still fast enough