【问题标题】:C# 9 - How to call default interface method with reflection?C# 9 - 如何使用反射调用默认接口方法?
【发布时间】:2021-03-10 12:12:40
【问题描述】:

我有一个自动映射器的接口。 DTO 实现了这个接口。如您所见,有一个默认方法。

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 });
        }
    }
}

如何调用默认接口方法?

【问题讨论】:

  • 所以?这如何阻止您使用扩展方法?
  • 您不了解 DIM 的工作原理。您需要在任何地方添加一些额外的东西。你不能从ItemDto 内部调用Mapping() 甚至base.Mapping。你必须cast 到IMap,即((IMap&lt;Item&gt;)this).Mapping()。从外部来看,调用Mapping 的唯一方法是通过IMap 接口,通过强制转换或使用IMap 参数和值。顺便说一句,这也是显式接口实现的工作原理
  • 在这种情况下,方法的名称是IMap&lt;TItem&gt;.Mapping 而不仅仅是Mapping

标签: c# reflection default-interface-member


【解决方案1】:

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

// 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 });
}

【讨论】:

  • 我把var mapInterface = type.GetInterfaces()[0];的那行改成var mapInterface = type.GetInterfaces().FirstOrDefault(w =&gt; w.Name.Remove(w.Name.IndexOf('`')) == "IMap");
猜你喜欢
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 2016-10-12
  • 2020-04-11
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
相关资源
最近更新 更多