gpt4 book ai didi

c# - 使用动态注入(inject)类创建委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 17:29:21 26 4
gpt4 key购买 nike

我正在改变我从反射到委托(delegate)的处理算法,因为它处理大量数据并且存在性能问题(据我所知 here )。所以我的旧代码是一个简单的反射,如下所示:

var result = method.Invoke(service, new object[] { viewModel });

方法是 MethodInfoservice 是一个服务类,它有一个名为 Add() 的通用方法。所有服务都有该方法(不是通用的),并且该处理算法可以在任何服务上运行,因此,服务(实例)是动态的。使用 Unity 解决。

这是一个working demo使用我正在尝试实现的类似代码:

using System;
using System.Reflection;

// This is the delegate declaration
public delegate string ServiceDelegate(ViewModel vm);

public class Program
{
public static void Main()
{
// Here the 'Service' class is created by a IoC container
object service = DependencyInjectionSimulator.Resolve();
Type type = service.GetType();
MethodInfo method = type.GetMethod("Add");

ServiceDelegate serviceDelegate = (ServiceDelegate)Delegate.CreateDelegate(typeof(ServiceDelegate), service, method);

var car = new CarViewModel();

Console.WriteLine(serviceDelegate(car));
}
}

// This is the 'Service' base class. It will be created dynamically and all services has the Add() method with a 'ViewModel' inherited class
public class Service
{
public string Add(CarViewModel input)
{
return input.Name;
}
}

// All 'Add()' method of services will work with a parameter that inherits 'ViewModel'
public class ViewModel
{
public string Name { get; set; }
}

public class CarViewModel : ViewModel
{
}

// Let's pretend this is a Unity Resolver
public static class DependencyInjectionSimulator
{
public static object Resolve()
{
return new Service();
}
}

我希望这能澄清我正在努力实现的目标,尽管我不确定这是否可能。

最佳答案

您的 DI 框架只会为您提供一个委托(delegate)您所要求的类型的对象,因此您永远不必担心委托(delegate)或反射。例如,让我们将您的 DI 模拟器更新为:

public static class DependencyInjectionSimulator
{
public static TService Resolve<TService>()
where TService : class
{
//So this only works for the one type right now, but hey, it's only a simulator!
return new Service() as TService;
}
}

我还建议您为您的服务使用一个接口(interface),这是一个养成的好习惯,并且在将来进行单元测试之类的事情时会有所帮助:

public interface IService
{
void Add(CarViewModel input);
}

public class Service : IService
{
public void Add(CarViewModel input)
{

}
}

现在您的代码简化为:

var service = DependencyInjectionSimulator.Resolve<IService>();
var car = new CarViewModel();
service.Add(car);

关于c# - 使用动态注入(inject)类创建委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51305504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com