使用泛型执行类的反射 [英] Reflection To Execute Class With Generic Type

查看:90
本文介绍了使用泛型执行类的反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用反射(查找接口实现)找到它之后,我想在使用泛型类型的类上动态执行一个方法。

I would like to dynamically execute a method on a class that uses a generic type, after finding it using reflection (which looks for an interface implementation).

下面是我卡住的示例。非常感谢您的帮助。

An example of where I am stuck is below. Help is much appreciated.

设置

public interface IActionRequired<T> where T : class {
    void DoThis(T[] receivedObjects);
}

public class BookDetails {
    public int BookId { get; set; }

    public string BookName { get; set; }
}

public class LibraryBookReturned : IActionRequired<BookDetails>
{
    public void DoThis(BookDetails[] receivedObjects)
    {
        foreach(var book in receivedObjects)
            System.Console.WriteLine(book.BookName);
    }
}

使用反射尝试的示例

下面,我只是使用第一个实现,但在现实世界中,我将使用命名约定来找到正确的实现。

Below, I am just using the first implementation but in the real world I'll be using a naming convention to locate the correct implementation.

        var assembly = Assembly.GetCallingAssembly();
        var listOfImplementations = 
                GetAllTypesImplementingOpenGenericType(typeof(IActionRequired<>), assembly);
        var implementation = listOfImplementations.FirstOrDefault();
        var implementationUsesInterface = implementation.GetInterfaces() [0];
        var interfaceUsesType = implementationUsesInterface.GetGenericArguments() [0];

我了解以下内容不起作用(我收到一条错误消息,指出interfaceUsesType是变量而不是类型),但它表示我想做什么:

I understand that the below will not work (I get an error saying interfaceUsesType is a variable not a type) but it indicates what I would like to do:

        var instance = 
            assembly.CreateInstance(implementation.FullName) as IActionRequired<interfaceUsesType>;
        var results = this.CheckForMessages<interfaceUsesType>();
        instance.DoThis(results);


推荐答案

@rickvbosch的答案(几乎)是什么我需要而且绝对是正确的方法。但是,由于我试图有效地做两件事,所以我对他的回答表示赞同,并使用他的建议补充了我所做的使事情作为我最初的问题的可接受答案的事情。

@rickvbosch 's answer was (very nearly) what I needed and definitely the right way to go. However, since I was trying to do two things effectively, I've upvoted his answer and added what I did to get things working as the accepted answer to my original problem, using his suggestion.

        var instance = Activator.CreateInstance(implementation);
        var results = this.GetType()
            .GetMethod("CheckForMessages", BindingFlags.NonPublic | BindingFlags.Instance)
            .MakeGenericMethod(interfaceUsesType)
            .Invoke(this, null) as object[];

        if(results.Count() > 0)
            instance.GetType()
            .GetMethod("DoThis")
            .Invoke(instance, new object[] {results});

这篇关于使用泛型执行类的反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆