看看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/