看看setAccessible - Java中的一种方法,可让您通过反射调用私有方法。为什么.NET没有实现这样的功能呢?为什么在.NET中没有Java的setAccessible?
3
A
回答
5
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");
}
}
2
我想,“为什么”,可能会有点投机问题的例子,但如果你正在寻找一种方式来测试私有方法,我想你就可以使用.NET 4.0这样做更容易:
http://bugsquash.blogspot.com/2009/05/testing-private-methods-with-c-40.html
4
您可以使用反射来调用私有方法,虽然它不是直线前进的调用公共方法。我们已经进行单元测试之前完成这一点,并使用了以下职位为如何做参考:
http://www.emadibrahim.com/2008/07/09/unit-test-private-methods-in-visual-studio/
http://johnhann.blogspot.com/2007/04/unit-testing-private-methods.html
2
它在.NET很可能获得访问任何私人使用反射。
E.g得到ACCES上课栏上叫Foo的私有实例方法看起来像:
typeof(Bar).GetMethod("Foo",BindingFlags.NonPublic | BindingFlags.Instance);
但它确实需要使用反射的代码是完全可信的。
(V4的安全要求会有所不同)
相关问题
- 1. 为什么在java中没有sizeof
- 2. 为什么.NET中没有ArgumentEmptyException?
- 3. 为什么Java中没有“Equlable”接口?
- 4. 为什么Java中没有静态类
- 5. 为什么在.NET中没有IDateTimeProvider并且DateTime具有Now getter?
- 6. 为什么没有.NET社区过程?
- 7. 为什么没有.NET RuntimePropertyHandle和PropertyInfo.GetPropertyFromHandle?
- 8. 为什么Java在Java中没有指针时会出现“NullPointerException”?
- 9. 为什么事件在.NET中没有返回类型?
- 10. 为什么没有Dispose方法在.Net Core中重写?
- 11. 为什么Java中没有内存区域没有gc发生?
- 12. 为什么在java 8中没有原始的BiConsumer?
- 13. 为什么Java 8没有“myArray.stream()”函数?
- 14. 为什么Java没有文件拷贝?
- 15. 为什么System.Numerics.BigInteger在Silverlight 4.0中没有Parse方法,但在.Net 4.0中有?
- 16. .NET框架中为什么没有托管的MD5实现?
- 17. 为什么.NET没有内置的像Java一样的Observer模式?
- 18. 为什么在Java SE 6 apidoc中没有记录com.sun.media.sound包?
- 19. 为什么Long值在java中没有正确打印?
- 20. 为什么在java中没有办法通过引用传递
- 21. 为什么在Java中没有@Implements注释?
- 22. 为什么Java在Map中没有putIfAbsent(key,supplier)方法?
- 23. 为什么在Java中没有WeakList和WeakSet实现?
- 24. 为什么在这个java代码中没有竞争条件?
- 25. 为什么在java中有变量
- 26. Java中有没有.NET的NotImplementedException异常?
- 27. 为什么在CSS中没有继承
- 28. 为什么在Scala中没有tailOption?
- 29. 为什么CFStringEncodings在Swift中没有UTF8?
- 30. 为什么在RandomAccessFile类中没有readUnsignedInt?
链接已损坏。如果你在从网站上抄下有用的内容之前,它们会很好,现在这个被接受的答案是没有用的。 – NightOwl888 2016-10-13 14:00:45
@ NightOwl888,为你修好。 – Yishai 2016-10-13 15:06:54