2010-06-04 35 views

回答

1

有很多的方式來使用它。我使用它的一種方式是在單元測試中,當我需要破壞一些私有變量以使單元測試失敗時(模擬失敗測試場景)。例如,如果我想模擬數據庫連接失敗,那麼我可以使用下面的方法在與數據庫一起工作的類中更改connectionString私有變量。當我嘗試連接到數據庫時,這會導致數據庫連接失敗,並且在我的單元測試中,我可以驗證是否引發了適當的異常。

例:

/// <summary> 
/// Uses reflection to set the field value in an object. 
/// </summary> 
/// 
/// <param name="type">The instance type.</param> 
/// <param name="instance">The instance object.</param> 
/// <param name="fieldName">The field's name which is to be fetched.</param> 
/// <param name="fieldValue">The value to use when setting the field.</param> 
internal static void SetInstanceField(Type type, object instance, string fieldName, object fieldValue) 
{ 
    BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic 
     | BindingFlags.Static; 
    FieldInfo field = type.GetField(fieldName, bindFlags); 
    field.SetValue(instance, fieldValue); 
} 
2

一個真實的案例:

一個功能,當通過了命名空間的名字看起來通過命名空間中的所有類,如果發現一個函數「自檢」它調用它的類,如果需要的話實例化一個對象。

這讓我申報測試功能爲對象的一部分,而不是擔心維護的測試列表。

0

請參閱Microsoft如何使用它在web.config中例如:)

我用它當我有篩選項目(使用ItemFilter屬性)從Autocompletebox。 ItemSource是用Linq設置的。由於每個項目都是AnonymousType,我使用Reflection來獲取屬性並執行我期望的過濾器。

1

雲南財貿是一種技術,它允許開發者在運行時訪問類型/實例的元數據
最常見的用法是定義CustomAttribute並在運行時使用它

Reflection. What can we achieve using it?

1

一般來說任何觸動System.Type類型可以這樣認爲:CustomAttribute已奧姆斯,ASP.Net ActionFilter,單元測試框架等

科裏查爾頓被用來在這個問題回答得非常好反射。對於各種各樣的場景,這通常是有用的(除其他外)。

要在其中創建類型的實例,你不知道,直到運行時考慮這樣一個例子:

public interface IVegetable { 
    public float PricePerKilo {get;set;} 
} 

public class Potato : IVegetable { 
    public float PricePerKilo {get;set;} 
} 

public class Tomato : IVegetable { 
    public float PricePerKilo {get;set;} 
} 

public static class Program { 
    public static void Main() { 
    //All we get here is a string representing the class 
    string className = "Tomato"; 
    Type type = this.GetType().Assembly.GetType(className); //reflection method to get a type that's called "Tomato" 
    IVegetable veg = (IVegetable)Activator.CreateInstance(type); 
    } 
} 
+0

+1從來沒有聽說過「約定配置」,聽起來像個好主意。我自己也做過類似的事情,但這需要我在實驗中做的事情,並進一步進行10步。 – 2010-06-04 03:35:47

0

我用它來驗證/編碼,想通過在一個類中的所有字符串期待並在我發送到Web視圖之前將它們更改爲HTML安全字符串。當從視圖中檢索數據時相似,我通過編碼/正則表達式運行,以確保只使用安全的html字符。

另一種方法是在C#中編寫插件,您希望在運行時知道該功能。來自代碼項目的示例:http://www.codeproject.com/KB/cs/pluginsincsharp.aspx

0

我已經使用它來編譯Web應用程序頁面內的控件列表(從一個完全獨立的頁面)。

它可以用來動態實例化類,分析組件,類型檢查...

它是什麼,它說,反射,它允許一個程序來看待自己。

相關問題