[英]How can I add a method to a list of actions via reflection?
我創建了一個dot.net fiddle ,它顯示了實際需求。
基本上我有很多業務類繼承自基類 class。我希望能夠動態地向所有這些業務類添加邏輯,以便在它們創建實體后執行。
在這種特定情況下,我希望能夠記錄創建的實體。
這是我的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
var businessClasses = typeof(IEntity)
.Assembly
.GetTypes()
.ToList()
.Where(i => i.BaseType != null)
.Where(i => i.BaseType.Name.StartsWith("Business"))
.ToList();
Console.WriteLine(businessClasses.Count);
foreach (var businessClass in businessClasses)
{
var postCreationAugmenters = businessClass.GetField("PostCreationAugmenters", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static).GetValue(null);
// how can I add the LogAugmenter.LogCreation to the postCreationAugmenters list?
}
public static class LogAugmenter
{
public static void LogCreation(IEntity entity)
{
}
}
public interface IEntity
{
long Id { get; set; }
}
public class Blog : IEntity
{
public long Id { get; set; }
}
public class Business<T>
where T : IEntity
{
public static List<Action<T>> PostCreationAugmenters = new List<Action<T>>();
public T Create(T entity)
{
// Inserting the model inside the database and returning it with the assigned Id
foreach (var augmenter in PostCreationAugmenters)
{
augmenter.Invoke(entity);
}
return entity;
}
}
public class BlogBusiness : Business<Blog>
{
}
如何將LogAugmenter.LogCreation
添加到通過反射提取的postCreationAugmenters
列表中。
您必須按照以下步驟將您的方法添加到通用列表中:
List.Add
方法。List.Add
並傳遞創建委托。看看這個例子,但正如評論中提到的,我認為你選擇這個設計沒有任何好處。 使用接口的類型安全方法將使您免於許多難以維護和調試的反射調用。
foreach (var businessClass in businessClasses)
{
var postCreationAugmenters = businessClass.GetField("PostCreationAugmenters", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static).GetValue(null);
// how can I add the LogAugmenter.LogCreation to the postCreationAugmenters list?
var targetMethod = typeof(LogAugmenter).GetMethod(nameof(LogAugmenter.LogCreation));
var targetMethodDelegate = Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(businessClass.BaseType.GetGenericArguments()), targetMethod);
var listAddMethod = postCreationAugmenters.GetType().GetMethod("Add");
listAddMethod.Invoke(postCreationAugmenters, new object[] { targetMethodDelegate });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.