【问题标题】:What is reflection and what can it be used for in c#? [duplicate]什么是反射,它在 c# 中可以用来做什么? [复制]
【发布时间】:2011-02-27 14:27:35
【问题描述】:

可能重复:
Reflection. What can we achieve using it?

我看到很多在 c# 中使用反射的例子,但我不确定它在 c# 中主要用于什么。那你什么时候用呢?

【问题讨论】:

标签: c# reflection system.reflection


【解决方案1】:

真实案例:

一个函数在传递命名空间的名称时会查看命名空间中的所有类,如果它在调用它的类中找到一个函数“SelfTest”,则在需要时实例化一个对象。

这让我可以将测试函数声明为对象的一部分,而不必担心维护测试列表。

【讨论】:

    【解决方案2】:

    有很多方法可以使用它。我使用它的一种方法是在单元测试中,当我需要破坏一些私有变量以使单元测试失败(模拟失败测试场景)时。例如,如果我想模拟数据库连接失败,那么我可以使用下面的方法来更改与数据库一起使用的类中的 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);
    }
    

    【讨论】:

      【解决方案3】:

      重选是一种允许开发人员在运行时访问类型/实例的元数据的技术。
      最常见的用法是定义 CustomAttribute 并在 运行时 使用它。 CustomAttribute 已用于 ORMs、ASP.Net ActionFilter、单元测试框架等。

      Cory Charlton 在这个问题上回答得很好:

      Reflection. What can we achieve using it?

      【讨论】:

        【解决方案4】:

        一般来说,任何涉及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);
          }
        }
        

        【讨论】:

        • +1 从未听说过“约定优于配置”,听起来是个好主意。我自己也做过类似的事情,但这比我在实验中所做的还要多 10 步。
        【解决方案5】:
        【解决方案6】:

        例如,查看 Microsoft 如何在 web.config 中使用它:)

        当我必须从 Autocompletebox 过滤项目(使用 ItemFilter 属性)时,我使用了它。 ItemSource 是用 Linq 设置的。由于每个项目都是 AnonymousType,我使用反射来获取属性并执行我想要的过滤器。

        【讨论】:

          【解决方案7】:

          我将它用于验证/编码,例如查看类中的所有字符串并将它们更改为 HTML 安全字符串,然后再发送到 Web 视图。同样,从视图中检索数据时,我通过编码/正则表达式运行以确保仅使用安全的 html 字符。

          另一种方法是用 C# 编写插件,您希望在运行时知道该功能。代码项目示例:http://www.codeproject.com/KB/cs/pluginsincsharp.aspx

          【讨论】:

            【解决方案8】:

            我用它来编译 Web 应用程序的页面(来自完全独立的页面)内的控件列表。

            可用于动态实例化类、分析程序集、类型检查...

            这就是它所说的,一种反射,它允许程序查看自己。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-02-13
              • 2013-07-31
              • 2010-09-07
              • 1970-01-01
              • 2011-01-19
              • 1970-01-01
              相关资源
              最近更新 更多