【发布时间】:2011-02-27 14:27:35
【问题描述】:
【问题讨论】:
-
Reflection. What can we achieve using it? 的可能重复项 - 以及大约 50 个其他问题。
标签: c# reflection system.reflection
【问题讨论】:
标签: c# reflection system.reflection
真实案例:
一个函数在传递命名空间的名称时会查看命名空间中的所有类,如果它在调用它的类中找到一个函数“SelfTest”,则在需要时实例化一个对象。
这让我可以将测试函数声明为对象的一部分,而不必担心维护测试列表。
【讨论】:
有很多方法可以使用它。我使用它的一种方法是在单元测试中,当我需要破坏一些私有变量以使单元测试失败(模拟失败测试场景)时。例如,如果我想模拟数据库连接失败,那么我可以使用下面的方法来更改与数据库一起使用的类中的 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);
}
【讨论】:
重选是一种允许开发人员在运行时访问类型/实例的元数据的技术。
最常见的用法是定义 CustomAttribute 并在 运行时 使用它。 CustomAttribute 已用于 ORMs、ASP.Net ActionFilter、单元测试框架等。
Cory Charlton 在这个问题上回答得很好:
【讨论】:
一般来说,任何涉及System.Type 类型的东西都可以被认为是反射。对于各种Convention over Configuration 场景,它通常很有用(除其他外)。
考虑一个示例,您希望创建一个直到运行时才知道的类型的实例:
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);
}
}
【讨论】:
例如,查看 Microsoft 如何在 web.config 中使用它:)
当我必须从 Autocompletebox 过滤项目(使用 ItemFilter 属性)时,我使用了它。 ItemSource 是用 Linq 设置的。由于每个项目都是 AnonymousType,我使用反射来获取属性并执行我想要的过滤器。
【讨论】:
我将它用于验证/编码,例如查看类中的所有字符串并将它们更改为 HTML 安全字符串,然后再发送到 Web 视图。同样,从视图中检索数据时,我通过编码/正则表达式运行以确保仅使用安全的 html 字符。
另一种方法是用 C# 编写插件,您希望在运行时知道该功能。代码项目示例:http://www.codeproject.com/KB/cs/pluginsincsharp.aspx
【讨论】:
我用它来编译 Web 应用程序的页面(来自完全独立的页面)内的控件列表。
可用于动态实例化类、分析程序集、类型检查...
这就是它所说的,一种反射,它允许程序查看自己。
【讨论】: