اجعل طريقة استدعاء طريقة الانعكاس هذه
-
01-10-2019 - |
سؤال
class CustomerMessage
{
private string name;
private Dictionary<MethodBase, object> changeTrackingMethods =
new Dictionary<MethodBase, object>();
public int Id { get; set; }
public string Name {
get { return this.name; }
set
{
this.name = value;
this.PropertyChanged("SetName", value);
}
}
private void PropertyChanged(string behaviorMethod, object value)
{
var method = typeof(Customer).GetMethod(behaviorMethod);
this.changeTrackingMethods.Add(method, value);
}
public void ApplyChanges(Customer c)
{
foreach (var changedProperty in this.changeTrackingMethods)
changedProperty.Key.Invoke(c, new object[] {
changedProperty.Value
});
}
}
كما ترون أنني أتتبع التغييرات على هذه الرسالة الواردة ، لتشغيل التغييرات على كائن آخر. يتم تمرير طريقة التشغيل إلى PropertyChanged كسلسلة. هل لدى أي شخص نصيحة كيف يمكنني جعل هذا النوع آمنًا؟
المحلول
شيء من هذا القبيل؟
class CustomerMessage
{
private string name;
private List<Action<Customer>> changeTrackingMethods =
new List<Action<Customer>>();
public int Id { get; set; }
public string Name {
get { return this.name; }
set
{
this.name = value;
this.changeTrackingMethods.Add(c => { c.SetName(value) });
}
}
public void ApplyChanges(Customer c)
{
foreach (var action in this.changeTrackingMethods)
{
action(c);
}
}
}
نصائح أخرى
هل تريد تجنب تمرير اسم الطريقة كسلسلة؟ لماذا لا تحصل على كائن Methodbase في Setter؟
public string Name {
get { return this.name; }
set
{
this.name = value;
this.PropertyChanged(typeof(Customer).GetMethod(behaviorMethod), value);
}
}
private void PropertyChanged(MethodBase method, object value)
{
this.changeTrackingMethods.Add(method, value);
}
بدلاً من تخزين "العملية التي يجب القيام بها" كزوج من الأسلوب والحجة التي ينبغي نقلها إليها باستخدام التفكير ، يمكنك تخزين مندوب يجب تنفيذه. أبسط طريقة للقيام بذلك هي تخزين قائمة من النوع List<Action<Customer>>
- ثم في ApplyChanges
الطريقة ، يمكنك التكرار على القائمة وتشغيل جميع الإجراءات.
في حال كنت لا تستخدم .NET 3.5 و C# 3.0 (الذي يحدد مندوبًا عامًا Action
ويدعم تعبيرات Lambda) ، لا يزال بإمكانك كتابة هذا في C# 2.0:
// you can define a delegate like this
delegate void UpdateCustomer(Customer c);
// and you could use anonymous methods
// (instead of more recent lambda expressions)
list.Add(delegate (Customer c) { c.SetName("test"); });
تحرير: يبدو أنني كنت أبطأ في كتابة الكود ، لكنني سأبقي هذا هنا كتفسير - الحل الذي قام به "DTB" يفعل بالضبط ما وصفته.