以下 C# 代碼示例顯示了如何使用引用來修改裝箱的值類型。
using System; using System.Reflection; using System.Reflection.Emit; using System.Threading; using System.Collections; class bug { // Suppose you have an API element that exposes a // field through a property with only a get accessor. public object m_Property; public Object Property { get { return m_Property;} set {m_Property = value;} // (if applicable) } // You can modify the value of this by doing // the byref method with this signature. public static void m1( ref int j ) { j = Int32.MaxValue; } public static void m2( ref ArrayList j ) { j = new ArrayList(); } public static void Main(String[] args) { Console.WriteLine( "http:////// doing this with value type" ); { bug b = new bug(); b.m_Property = 4; Object[] objArr = new Object[]{b.Property}; Console.WriteLine( b.m_Property ); typeof(bug).GetMethod( "m1" ).Invoke( null, objArr ); // Note that the property changed. Console.WriteLine( b.m_Property ); Console.WriteLine( objArr[0] ); } Console.WriteLine( "http:////// doing this with a normal type" ); { bug b = new bug(); ArrayList al = new ArrayList(); al.Add("elem"); b.m_Property = al; Object[] objArr = new Object[]{b.Property}; Console.WriteLine( ((ArrayList)(b.m_Property)).Count ); typeof(bug).GetMethod( "m2" ).Invoke( null, objArr ); // Note that the property does not change. Console.WriteLine( ((ArrayList)(b.m_Property)).Count ); Console.WriteLine( ((ArrayList)(objArr[0])).Count ); } } } 確保方法訪問的安全某些方法可能不適合由不受信任的任意代碼調用它們。此類方法會導致幾個風險:方法可能會提供某些受限制信息;可能會相信傳遞給它的任何信息;可能不會對參數進行錯誤檢查;或者,如果參數錯誤,可能會出現故障或執行某些有害操作。您應當注意這些情況,并采取適當的操作來確保方法的安全。
在某些情況下,您可能需要限制不打算公開使用、但仍必須是公共的方法。例如,您可能有一個需要在自己的 DLL 之間進行調用的接口,因此它必須是公共的,但您不想公開它,以防止用戶使用它或防止惡意代碼利用它作為入口點進入到您的組件中。對不打算公共使用(但仍必須是公共)的方法進行限制的另一個常見理由是,避免用文檔記錄和支持非常內部的接口。
托管代碼為限制方法訪問提供了幾個方式:
•將可訪問性的作用域限制到類、程序集或派生類(如果它們是可信任的)。這是限制方法訪問的最簡單方式。請注意,通常派生類的可信賴度比它們派生自的類更低,但在某些情況下,它們可以共享超類標識。特別是,不要從關鍵字 protected 推斷信任情況,因為在安全上下文中,該關鍵字不是必須使用的。
•將方法訪問限制到指定標識(實質上,是您選擇的任何特殊證據)的調用方。
•將方法訪問限制到擁有您所選權限的調用方。
文章來源于領測軟件測試網 http://www.kjueaiud.com/