2010-06-04 91 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应用程序页面内的控件列表(从一个完全独立的页面)。

它可以用来动态实例化类,分析组件,类型检查...

它是什么,它说,反射,它允许一个程序来看待自己。

相关问题