如何使用反射来调用库中存在的内部类的方法? [英] How can I use reflection to invoke a method on this internal class that exists in a library?

查看:235
本文介绍了如何使用反射来调用库中存在的内部类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内部类的C#项目库DLL,我想对它进行单元测试。如果可能的话,我想通过使用反射来引用它来专门单元测试这个内部类。



我有这个类:

 命名空间ProjectA.BC 
{
类缓存
{
public static void DoWork(){}
}
}

如何调用 DoWork 方法使用来自另一个使用 ProjectA 的项目的反射?我已经尝试了,但是我的第一个问题是 typeof(ProjectA.BCCaching)被保护,所以我似乎甚至不能得到类型引用,但我是确定有一种方法。



错误是:


'ProjectA。 BCCaching'由于其保护级别无法访问



解决方案

可以使用InternalsVisibleToAttribute进行您的单元测试项目可以看到内部类。



https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v = vs.110)。 aspx


I have a C# project library DLL with an internal class, and I want to unit test it. I want to specifically unit test this internal class by getting a reference to it using reflection, if possible.

I have this class:

namespace ProjectA.B.C
{
    class Caching
    {
        public static void DoWork() { }
    }
}

How can I call the DoWork method using reflection from another project that uses ProjectA? I have tried, but my first issue is that typeof(ProjectA.B.C.Caching) is protected so I can't seem to even get the type reference yet, but I'm sure there is a way.

The error is :

'ProjectA.B.C.Caching' is inaccessible due to its protection level

解决方案

You can use the InternalsVisibleToAttribute to make the internal class visible to your unit test project.

https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx

这篇关于如何使用反射来调用库中存在的内部类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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