java - 为什么在 .NET 中没有与 Java 的 setAccessible 类似的东西?

标签 java .net reflection

看看setAccessible - Java 中一种让您通过反射调用私有(private)方法的方法。为什么 .NET 还没有实现这样的功能?

最佳答案

Here是在 .NET 中执行此操作的示例

using System;
using System.Reflection;
using System.Collections.Generic;

public class MyClass
{
   public static void Main()
   {
        try
        {
            Console.WriteLine("TestReflect started.");
            TestReflect test = new TestReflect();
            Console.WriteLine("TestReflect ended.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        ConsoleKeyInfo cki;
        do
        {
            Console.WriteLine("Press the 'Q' key to exit.");
            cki = Console.ReadKey(true);
        } while (cki.Key != ConsoleKey.Q);
   }
}

public class TestReflect
{
   public TestReflect()
   {
        this.GetType().GetMethod("PublicMethod").Invoke(this, null);
        this.GetType().GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
   }

   public void PublicMethod()
   {
        Console.WriteLine("PublicMethod called");
   }

   private void PrivateMethod()
   {
        Console.WriteLine("FTW!one1");
   }
 }

关于java - 为什么在 .NET 中没有与 Java 的 setAccessible 类似的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/966794/

相关文章:

java - Ant 在哪里设置它的 'java.home'(这是错误的)并且它应该附加 '/jre' 吗?

c# - .NET HttpClient : How to set the request method dynamically?

用于测试私有(private)方法的 Java 工具?

c# - 如何通过反射调用泛型方法

java - 实例方法是否曾经使用静态绑定(bind)解析?

java - 将 double 向下转型为 int 哪种舍入模式?

.net - 使用 MONO_IOMAP 来处理硬编码文件路径?

c# - 动态添加的标签不出现

Scala-如何获取 Vector 的包含类?

java - 创建不封装的属性