[英]Action<T> equivalent for properties
我有一個類實例化兩個實現接口的類。 我想要一個類通知另一個類,某些東西沒問題。 我可以用Action執行它然后在類中使用私有變量但是想知道是否有直接的方法來使用屬性,這樣當屬性的值更改時它會更新另一個類的屬性。
例如:
public class MyClass
{
public ILogger Logger {get;set;}
public ILogic Logic {get;set;}
private Form MyWinform;
public void Setup()
{
MyWinform = new MyWinform();
MyWinform.StartBatch += Logger.CreateFile; //Create file when user presses start
//How can I set a property on ILogic to be AllOk once ILogger says so??
//I could use an Action so that once all is ok I call IDecidedAlOK in ILogger which
//can then assign a private bool variable inside the class
Logic.ItsOKMethodSoSetVariableToTrue = Logger.IDecidedAllOKMethod;
}
public void DataIn(string Value)
{
Logic.DataIn(Value);
}
public void CreateInstances()
{
Logger = new FileLogger();
Logic = new MyLogic();
}
}
public class MyLogic : ILogic
{
public void DataIn(string Value)
{
//I want to check that all is ok before I do anything
//if (!AllOK)
//return;
//Do stuff
}
}
實現INotifyPropertyChanged
接口並訂閱PropertyChanged
事件
我覺得讓ILogger接口暴露類似“FileCreated”或“Ready”事件可能會更常規,並允許您的應用程序處理該事件以更新ILogic對象(或做任何其他必要的事情) )。
編輯:道歉,在重新閱讀問題之后,我想我誤解了你的要求。
沒有任何“自然”對象可以完全滿足您的要求,但您可以為此創建一個匿名委托(或lambda表達式):
Action<bool> loggerResult = (value) => Logic.ItsOKMethodSoSetVariableToTrue = value;
一個屬性內部由兩個私有方法組成,一個是get_XXX和一個set_XXX,所以除非你想獲取那些方法的MethodInfo並調用它們(它們再次是方法),否則你別無選擇,只能實現方法調用方法。
訂閱事件( INotifyPropertyChanged
或一些自定義的)是正常的,傳遞lambda-setter的方法也是如此,但在某些情況下,使用共享上下文對象可能更方便(很像共享內存概念):
class ConversationContext
{
public bool EverythingIsOK { get; set;}
}
該對象被傳遞給所有感興趣的對象( ILogic
和ILogger
),它們直接在它上面運行,而不是一些內部屬性。 如果需要更改通知,請在其上實施INotifyPropertyChanged
。
這種方法的一個積極方面是你不會糾結於反復觸發事件觸發其他事件等等。 單個對象將保持當前狀態,不需要重復更新。
同樣,這只是眾多選擇中的一種。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.