它绝对是使用的良好实践吗?
在项目中,有哪些可能需要反射的情况?
它绝对是使用的良好实践吗?
在项目中,有哪些可能需要反射的情况?
反射有很多用途:
然而,我最喜欢使用反射来查找已标记属性的属性之一。
例如,我编写了标记我的类中应使用Lucene索引的属性的属性。在运行时,我可以查看任何类,并通过查询“标记”属性来确定哪些字段需要进行索引。
反射是一种在运行时检查对象的方法。如果您不需要这样做,就不应该使用它。
反射允许应用程序收集有关自身的信息并对其进行操作。它可以用于查找程序集中的所有类型和/或在程序集中动态调用方法。
System.Reflection:命名空间包含提供已加载类型、方法和字段的托管视图的类和接口,并具有动态创建和调用类型的能力,这个过程被称为.NET框架中的反射。
System.Type:类是.NET反射功能的主要类,也是访问元数据的主要途径。System.Type类是一个抽象类,表示公共类型系统(CLS)中的类型。
它代表类型声明:类类型、接口类型、数组类型、值类型、枚举类型、类型参数、泛型类型定义以及开放或关闭构造的泛型类型。
例如:
using System;
using System.Reflection;
static class ReflectionTest
{
public static int Height;
public static int Width;
public static int Weight;
public static string Name;
public static void Write()
{
Type type = typeof(ReflectionTest); // Get type pointer
FieldInfo[] fields = type.GetFields(); // Obtain all fields
foreach (var field in fields) // Loop through fields
{
string name = field.Name; // Get string name
object temp = field.GetValue(null); // Get value
if (temp is int) // See if it is an integer.
{
int value = (int)temp;
Console.Write(name);
Console.Write(" (int) = ");
Console.WriteLine(value);
}
else if (temp is string) // See if it is a string.
{
string value = temp as string;
Console.Write(name);
Console.Write(" (string) = ");
Console.WriteLine(value);
}
}
}
}
class Program
{
static void Main()
{
ReflectionTest.Height = 100; // Set value
ReflectionTest.Width = 50; // Set value
ReflectionTest.Weight = 300; // Set value
ReflectionTest.Name = "ShekharShete"; // Set value
ReflectionTest.Write(); // Invoke reflection methods
}
}
Output
Height (int) = 100
Width (int) = 50
Weight (int) = 300
Name (string) = ShekharShete
反射在IoC容器中经常被使用。假设你想要注册所有以单词“Controller”结尾的具体类,反射可以轻松实现。
我也曾经在单元测试类时使用反射来操作私有字段。
作为一个来自C++的程序员,我必须说is
关键字是非常宝贵的,特别是在需要一些简单的类层次结构时。
class MenuItem : Item { }
foreach(Item items in parent.ChildItems) {
if (item is MenuItem) { /* handle differently */ }
}
顺便说一句,反射是不是有点贵啊?