簡體   English   中英

如何通過反射將方法添加到操作列表中?

[英]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列表中。

您必須按照以下步驟將您的方法添加到通用列表中:

  1. 獲取目標方法。
  2. 為該方法創建一個匹配的委托。
  3. 獲取List.Add方法。
  4. 調用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM