2017-08-29 50 views
0

我是新來ReaciveUI和我進行了一些模擬測試來試試,看看它的功能,並建立它周圍的框架來自動執行某些事情。現在我已經到了想要觀察房產的地步,但我只知道它的名字。例如。WhenAny通過屬性名

public abstract class ViewModelBase : ReactiveObject 
{ 
     public ViewModelBase() 
     { 
      ObservePropertiesWithMyAttribute(); 
     } 

     private void ObservePropertiesWithMyAttribute() 
     { 
      foreach(var prop in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.GetCustomAttribute<MyAttribute>() != null)) 
      { 
       //Observe the property 
      } 
     } 
} 

是否有任何允許的超載?我來着幸福的想法(這顯然失敗):

foreach(var prop in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.GetCustomAttribute<MyAttribute>() != null)) 
{ 
    Expression<Func<string>> expression =() => prop.Name; 
    this.WhenAnyDynamic(expression.Body, x => x.Value).Subscribe(x => Text3 = $"Text is {x}"); 
} 

但它拋出一個System.NotSupportedException:「不支持的表達式類型:恆」

我知道我可以實現我通過想要的結果PropertyChanged方法,但我很好奇是否有這樣做的機會。

回答

0

您可以通過構建字符串來訪問該屬性的表達式。一旦你有了這個表達,你可以將它傳遞給WhenAny。這裏有一個例子:

class X : ReactiveObject 
{ 
    public X() 
    { 
     var propertyName = "A"; 
     this.WhenAny(GetProperty<int>(propertyName), c => c.GetValue() * c.GetValue()) 
      .Subscribe(i => Console.WriteLine(i)); 

    } 
    int _a; 
    public int A 
    { 
     get { return _a; } 
     set { this.RaiseAndSetIfChanged(ref _a, value); } 
    } 

    private Expression<Func<X, T>> GetProperty<T>(string propertyName) 
    { 
     ParameterExpression param = Expression.Parameter(typeof(X)); 
     Expression<Func<X, T>> expr = (Expression<Func<X, T>>)Expression.Lambda(
      Expression.Property(param, propertyName), 
      param 
     ); 
     return expr; 
    } 
} 
+0

鑑於這種情況,我確實需要知道實際的類的類型(在這種情況下,X)。我不能執行上一個基類(例如ViewModelBase),除非我改變的getProperty 成的getProperty 並通過反射MakeGenericMethod調用它,但不會是顯著影響性能? – rualmar

+0

如果你不知道在編譯時的類型,你會最終使用反射(或動態)的一種方式或其他。 – Shlomo

+1

儘管如此,ReactiveUI的一部分優勢在於編譯時檢查。如果你處於這種扭曲的水平,你可能應該只使用PropertyChanged。 – Shlomo