首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# 9-如何使用反射调用默认接口方法?

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

Stack Overflow用户
提问于 2021-03-10 20:12:41
回答 1查看 212关注 0票数 3

我有一个automapper的接口。DTO实现了这个接口。正如你所看到的,有一个默认的方法。

代码语言:javascript
复制
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; }
}

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

代码语言:javascript
复制
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 });
        }
    }
}

如何调用默认接口方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-10 20:53:33

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

代码语言:javascript
复制
// 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[] { ... });

要将此代码放入您的代码中,应如下所示:

代码语言:javascript
复制
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 });
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66564549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档