看看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. 爲什麼.NET 4.5中沒有CallerTypeNameAttribute?
- 2. 爲什麼.NET中沒有ArgumentEmptyException?
- 3. 爲什麼沒有在Java中
- 4. 爲什麼LinkedList在java中沒有initialCapacity?
- 5. 爲什麼在java中沒有sizeof
- 6. 爲什麼Java沒有宏?
- 7. 爲什麼.net項目沒有designer.cs?
- 8. 爲什麼沒有.NET社區過程?
- 9. 爲什麼沒有.NET RuntimePropertyHandle和PropertyInfo.GetPropertyFromHandle?
- 10. 爲什麼java中沒有頭文件?
- 11. 爲什麼Java中沒有靜態類
- 12. 爲什麼Java中沒有「Equlable」接口?
- 13. 爲什麼在.NET中沒有IDateTimeProvider並且DateTime具有Now getter?
- 14. int爲什麼沒有改變? java的
- 15. 爲什麼Java在Java中沒有指針時會出現「NullPointerException」?
- 16. 爲什麼.net 4.5沒有在註冊表中顯示
- 17. 爲什麼沒有Dispose方法在.Net Core中重寫?
- 18. 爲什麼在.net中沒有異步文件刪除?
- 19. 爲什麼事件在.NET中沒有返回類型?
- 20. 爲什麼Java中沒有內存區域沒有gc發生?
- 21. 爲什麼System.Numerics.BigInteger在Silverlight 4.0中沒有Parse方法,但在.Net 4.0中有?
- 22. .NET框架中爲什麼沒有託管的MD5實現?
- 23. 爲什麼在Java中的String.Replace之後沒有更改String值?
- 24. 爲什麼在java 8中沒有原始的BiConsumer?
- 25. 爲什麼Java 8沒有「myArray.stream()」函數?
- 26. Java爲什麼沒有ceil(float)?
- 27. 爲什麼Java沒有文件拷貝?
- 28. Java反射 - setAccessible的影響(true)
- 29. 爲什麼.NET沒有內置的像Java一樣的Observer模式?
- 30. Java中有沒有.NET的NotImplementedException異常?
鏈接已損壞。如果你在從網站上抄下有用的內容之前,它們會很好,現在這個被接受的答案是沒有用的。 – NightOwl888 2016-10-13 14:00:45
@ NightOwl888,爲你修好。 – Yishai 2016-10-13 15:06:54