反映了控制器列表 [英] Reflect Over List of Controllers

查看:146
本文介绍了反映了控制器列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点新在C#中的反映。我试图生成所有控制器的列表,以测试他们是否与特定actionfilter装饰。当编写单元测试,你是怎么进入测试组装?

这似乎不工作:

  VAR MyAssembly程序= System.Reflection.Assembly.GetExecutingAssembly();


解决方案

如果你知道在你的主组件类型,你可以使用:

 私人的IEnumerable<类型> GetControllers()
    {
        从吨的typeof返回(的MyType).Assembly.GetTypes()
               其中,t.IsAbstract ==假
               其中,typeof运算(控制器).IsAssignableFrom(T)
               其中,t.Name.EndsWith(控制器,StringComparison.OrdinalIgnoreCase)
               选择吨;
    }

与已知类型替换的MyType

我在基类中使用与 this.GetType()而不是 typeof运算(的MyType),所以我可以参考其中的组装的derrived类型的定义。

I'm a bit new to reflection in c#. I'm trying to generate a list of all controllers in order to test whether or not they are decorated with a specific actionfilter. When writing unit tests, how do you access the tested assembly?

This does not seem to work:

var myAssembly = System.Reflection.Assembly.GetExecutingAssembly();

解决方案

If you know a type in your main assembly, you can use:

    private IEnumerable<Type> GetControllers()
    {
        return from t in typeof(MyType).Assembly.GetTypes()
               where t.IsAbstract == false
               where typeof(Controller).IsAssignableFrom(t)
               where t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)
               select t;
    }

Replace MyType with the known type.

I use this in a base class with this.GetType() instead of typeof(MyType), so that I can reference the assembly in which the derrived type is defined.

这篇关于反映了控制器列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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