gpt4 book ai didi

C# 9 - 如何使用反射调用默认接口(interface)方法?

转载 作者:行者123 更新时间:2023-12-04 03:37:43 25 4
gpt4 key购买 nike

我有一个用于自动映射器的界面。并且 DTO 实现了这个接口(interface)。如您所见,有一个默认方法。

public interface IMap<T> {
public void Mapping(Profile profile) {
profile.CreateMap(typeof(T), GetType()).ReverseMap();
}
}

public class ItemDto : IMap<Item> {
public string Name { get; set; }
}

当我尝试调用此方法时。找不到方法。

public class MappingProfile : Profile {
public MappingProfile() {
ApplyMappingsFromAssembly();
}

private void ApplyMappingsFromAssembly() {
var types = AppDomain.CurrentDomain.GetAssemblies().Where(w => !w.IsDynamic).SelectMany(s => s.GetExportedTypes())
.Where(t => t.GetInterfaces().Any(i =>
i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMap<>)))
.ToList();

foreach (var type in types) {
var instance = Activator.CreateInstance(type);
var methodInfo = type.GetMethod("Mapping");
//In here I expect to call default interface method.
methodInfo?.Invoke(instance, new object[] { this });
}
}
}

如何调用默认接口(interface)方法?

最佳答案

您需要针对接口(interface)调用方法,这也包括通过反射获取方法。例如:

// Create the IMap<Item> type
var mapType = typeof(IMap<>).MakeGenericType(typeof(Item));

// Create the instance as you did before
var instance = Activator.CreateInstance(typeof(ItemDto));

// Get the method from the interface
var method = mapType.GetMethod("Mapping");

// Invoke the method
method.Invoke(instance, new object[] { ... });

为了使它适合您的代码,它看起来像这样:

foreach (var type in types)
{
// Cheating here by getting the first interface, so you might want to be cleverer
var mapInterface = type.GetInterfaces()[0];

// Get the generic type of the interface, e.g. "Item"
var genericType = mapInterface.GetGenericArguments()[0];

var instance = Activator.CreateInstance(type);
var mapType = typeof(IMap<>).MakeGenericType(genericType);
var methodInfo = mapType.GetMethod("Mapping");

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

关于C# 9 - 如何使用反射调用默认接口(interface)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66564549/

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