c# - 通过 System.Reflection 访问内部成员?

标签 c# .net reflection internal

我正在尝试对具有许多内部函数的类进行单元测试。这些显然也需要测试,但我的测试项目是独立的,主要是因为它涵盖了许多小的相关项目。到目前为止我所拥有的是:

FieldInfo[] _fields = 
    typeof(ButtonedForm.TitleButton).GetFields(
        BindingFlags.NonPublic | BindingFlags.Instance | 
        BindingFlags.DeclaredOnly);
Console.WriteLine("{0} fields:", _fields.Length);
foreach (FieldInfo fi in _fields)
{
    Console.WriteLine(fi.Name);
}

这很好地吐出了所有私有(private)成员,但仍然没有显示内部结构。我知道这是可能的,因为当我弄乱 Visual Studio 可以生成的自动生成的测试时,它会询问与向测试项目显示内部结构有关的事情。好吧,现在我正在使用 NUnit 并且真的很喜欢它,但是我怎样才能用它达到同样的目的呢?

最佳答案

使用 InternalsVisibleTo 会更合适属性以向单元测试程序集授予对程序集内部成员的访问权限。

这是一个包含一些有用的附加信息和演练的链接:

要真正回答您的问题... Internal 和 protected 在 .NET Reflection API 中不被识别。这是来自 MSDN 的引述:

The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly.

关于c# - 通过 System.Reflection 访问内部成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/171332/

相关文章:

c# - 为什么默认情况下域(业务逻辑)中的不变性不更常见?

c# - Double.IsNaN(double d) 的目的是什么?

c# - 您如何将 MONO Runtime 与您的应用程序打包在一起?

javascript - 给定对象在对象中的位置,如何修改对象属性

c# - 如何以编程方式重建现有程序集?

c# - .NET Core Scoped 通过 DI 在 Singleton 中调用

.net - .NET HttpWebRequest 中的压缩( header )错误?

c# - 声明一个常量数组

python - 如何按名称设置 Python 对象的字段/成员

c# - 添加到 List<t> 随着时间的推移变得非常慢