gpt4 book ai didi

c# - 在使用默认方法实现接口(interface)的类上使用 `GetMethod` 返回 null

转载 作者:行者123 更新时间:2023-12-05 03:48:47 31 4
gpt4 key购买 nike

我有几个接口(interface)(IMapFromIMapTo)可以简化我的AutoMapper 配置。每个接口(interface)都有 MapToMapFrom 方法的默认实现。我有一个单独的 MappingProfile 类,它使用反射来查找所有实现类,并调用它们的 map 创建。

前面提到的类看起来是这样的:

public interface IMapFrom<T>
{
void MapFrom(Profile profile) => profile.CreateMap(typeof(T), GetType());
}

public interface IMapTo<T>
{
void MapTo(Profile profile) => profile.CreateMap(GetType(), typeof(T));
}

public class MappingProfile : Profile
{
public MappingProfile()
{
ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
}

private void ApplyMappingsFromAssembly(Assembly assembly)
{
var types = assembly.GetExportedTypes()
.Where(t => t.GetInterfaces().Any(i =>
i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IMapFrom<>) ||
i.GetGenericTypeDefinition() == typeof(IMapTo<>))))
.ToList();

foreach (var type in types)
{
var instance = Activator.CreateInstance(type);
var mapTo = type.GetMethod("MapTo");
var mapFrom = type.GetMethod("MapFrom");
mapTo?.Invoke(instance, new object[] {this});
mapFrom?.Invoke(instance, new object[] {this});
}
}
}

如果实现接口(interface)的类覆盖了默认的接口(interface)实现,MappingProfile 类将按需要工作。但是,如果这些类仅依赖于默认实现,则 ApplyMappingsFromAssembly 方法中的 mapTomapFrom 都是 null。

例如,此类不会成功应用其映射:

public class CreateJobCommand : 
UpdateJobInputModel,
IMapFrom<UpdateJobInputModel>,
IMapTo<Job>,
IRequest<int>
{

}

如果默认实现没有在继承类中重新实现,我如何获得它们?

最佳答案

根据 Kevin Gosse 对我的问题的评论,我研究了使用 GetInterface().GetMethod(),如 Microsoft documentation 中所示.

如果我采用这种方法,现在可以运行的结果代码如下所示:

public class MappingProfile : Profile
{
public MappingProfile()
{
ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
}

private void ApplyMappingsFromAssembly(Assembly assembly)
{
var types = assembly.GetExportedTypes()
.Where(t => t.GetInterfaces().Any(i =>
i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IMapFrom<>) ||
i.GetGenericTypeDefinition() == typeof(IMapTo<>))))
.ToList();

foreach (var type in types)
{
var instance = Activator.CreateInstance(type);
var mapTo = type.GetMethod("MapTo") ??
instance!.GetType()
.GetInterface("IMapTo`1")?
.GetMethod("MapTo");
var mapFrom = type.GetMethod("MapFrom") ??
instance!.GetType()
.GetInterface("IMapFrom`1")?
.GetMethod("MapFrom");

mapTo?.Invoke(instance, new object[] {this});
mapFrom?.Invoke(instance, new object[] {this});
}
}
}

关于c# - 在使用默认方法实现接口(interface)的类上使用 `GetMethod` 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64233296/

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