[C#] 浅谈反射
admin
2023-08-02 15:50:14
0


入乡随俗的配图

在.NET中,反射(reflection)是一个运行库类型发现的过程。使用反射服务,可以通过编程使用一个友好的对象模型得到与通过ildasm.exe显示的相同元数据信息。

这段话引用自《精通C#》,通俗地讲就是,通过反射我们能在运行时获得程序或程序集所包含的所有类型的列表以及给定类型定义的方法、字段、属性和事件;还可以动态发现一组给定类型支持的接口、方法的参数和其他相关细节。

1. 反射的一个最直观的用法

我曾经在开发的时候遇到这样一个例子:在一个类A中增加了一些field,但是它们暂时不暴露给创建和修改类A的方法。但是又要保证这些field是可以通过专门的API来修改,所以要对每个field增加一对API来进行查看和修改。

然后我就写啊写啊,发现怎么这些API都是做的相同的事情,唯一不同的是函数名和访问的字段名。
所以,我就想,能不能只写一个函数来搞定这些事情呢?
于是就想到了反射,通过传进来参数表示要修改的字段名,然后动态地获取到该字段,并对它进行赋值或者读取它的值。

下面是一个简单的实例:

namespace ReflectionEx1
{
    public class ReflectionEx1
    {
        public int fieldInt { get; set; }
        public double fieldDouble { get; set; }
        public string fieldString { get; set; }
    }

    class Program
    {
        public static string GetFieldValue(string FieldName, object obj)
        {
            try
            {
                var property = obj.GetType().GetProperty(FieldName);
                if (property != null)
                {
                    object o = property.GetValue(obj, null);
                    return Convert.ToString(o);
                }

                Console.WriteLine(\"{0} does not have property {1}\", obj.GetType(), FieldName);
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }

        public static bool SetFieldValue(string FieldName, string Value, object obj)
        {
            try
            {
                var property = obj.GetType().GetProperty(FieldName);
                if (property != null)
                {
                    object v = Convert.ChangeType(Value, property.PropertyType);
                    property.SetValue(obj, v, null);
                    return true;
                }

                Console.WriteLine(\"{0} does not have property {1}\", obj.GetType(), FieldName);
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }       

        static void Main(string[] args)
        {
            var testClass = new ReflectionEx1();
            if (SetFieldValue(\"fieldInt\", \"1\", testClass))
            {
                Console.WriteLine(GetFieldValue(\"fieldInt\", testClass));
            }

            if (SetFieldValue(\"fieldDouble\", \"2.5\", testClass))
            {
                Console.WriteLine(GetFieldValue(\"fieldDouble\", testClass));
            }

            if (SetFieldValue(\"fieldString\", \"test\", testClass))
            {
                Console.WriteLine(GetFieldValue(\"fieldString\", testClass));
            }
        }
    }
}

这里所有的值都是通过string的方式进行转换的,所以在用SetFieldValue方法时传入的值是统一的string类型。这样在对某个域进行赋值时完全是看这个域的类型,然后尝试把string转成那个类型。如果我们外面调用的时候传入了错误的类型呢?

所以下面又写了另外一个版本,通过泛型来支持不同的类型,而不是通过string来转换。这样,当你试图用stringfieldInt进行赋值时会出现下面的异常:

Object of type \'System.String\' cannot be converted to type \'System.Int32\'.

namespace ReflectionEx1
{
    public class ReflectionEx1
    {
        public int fieldInt { get; set; }
        public double fieldDouble { get; set; }
        public string fieldString { get; set; }
    }

    class Program
    {
        public static T GetFieldValue(string FieldName, object obj)
        {
            try
            {
                var property = obj.GetType().GetProperty(FieldName);
                if (property != null)
                {
                    return (T)property.GetValue(obj, null);
                }

                Console.WriteLine(\"{0} does not have property {1}\", obj.GetType(), FieldName);
                return default(T);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return default(T);
            }
        }

        public static bool SetFieldValue(string FieldName, T Value, object obj)
        {
            try
            {
                var property = obj.GetType().GetProperty(FieldName);
                if (property != null)
                {
                    property.SetValue(obj, Value, null);
                    return true;
                }

                Console.WriteLine(\"{0} does not have property {1}\", obj.GetType(), FieldName);
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }       

        static void Main(string[] args)
        {
            var testClass = new ReflectionEx1();
            if (SetFieldValue(\"fieldInt\", 1, testClass))
            {
                Console.WriteLine(GetFieldValue(\"fieldInt\", testClass));
            }

            if (SetFieldValue(\"fieldDouble\", 2.5, testClass))
            {
                Console.WriteLine(GetFieldValue(\"fieldDouble\", testClass));
            }

            if (SetFieldValue(\"fieldString\", \"test\", testClass))
            {
                Console.WriteLine(GetFieldValue(\"fieldString\", testClass));
            }
        }
    }
}

不过,遗憾的是我最后并没有使用反射。因为这些暴露出来的API与类A是分离的东西,使用API的人并不是十分清楚类A的结构。也就是说你可以告诉用户,这个API是修改field1的,但是你不能妄想他们清楚地知道field1的名字(包括大小写)。这里看起来有点不合乎逻辑,既然他们知道是修改field1,为什么又不知道field1。举个例子,假设有一个布尔值field1,它被用来控制类A是否具有功能x。那么我们可以给用户提供一个API叫做EnableX(),这个API做的事情就是将field1设置为true(这个是不必暴露给用户的)。

2. 构建自定义的元数据查看器

上面的一个简单的例子可以看到我们可以在运行的时候通过反射,利用property的名字获取它。下面我们将自定义一个元数据查看器,通过这个例子来看看反射还能做到什么。

(1)反射方法

我们可以通过Type类的GetMethods()函数得到一个MethodInfo[]。下面我们利用它写一个ListMethods()方法,来输出传入类型的所有方法名。传入的类型可以是C#的内置类型(值类型和引用类型都行),也可以是自定义的类型。而调用ListMethods()方法时传的参数可以是利用对象的GetType()函数,也可以使用typeof运算符。

using System.Reflection;

namespace MyTypeViewer
{
    struct TestStruct
    {
        public void Func3() { }
    }

    public class TestClass
    {
        public void Func1() { }
        private void Func2() { }
    }

    class Program
    {
        static void ListMethods(Type type)
        {
            Console.WriteLine(\"***** Methods *****\");
            var methodNames = from m in type.GetMethods() select m.Name;
            foreach (var name in methodNames)
            {
                Console.WriteLine(\"-> {0}\", name);
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            var test = new TestClass();
            ListMethods(test.GetType());
            ListMethods(typeof(TestStruct));
            ListMethods(typeof(string));
        }
    }
}

下面的运行结果中由于string类的方法太多,所以省略了部分没有显示。

***** Methods *****
-> Func1
-> ToString
-> Equals
-> GetHashCode
-> GetType

***** Methods *****
-> Func3
-> Equals
-> GetHashCode
-> ToString
-> GetType

***** Methods *****
// ignore some methods
-> CopyTo
-> ToCharArray
-> IsNullOrEmpty
-> IsNullOrWhiteSpace
-> Split
-> Substring

这里或许你会有一个疑问,不是获取所有的方法吗?为什么TestClass.Func2没有显示呢?这是因为Func2是私有方法,而GetMethods()方法还有一个带参数的重写方法,参数为BindingFlags 枚举。

public abstract MethodInfo[] GetMethods(    
      BindingFlags bindingAttr
)

所以要读取私有的(private或者protected)方法,你需要在调用GetMethods()时传入参数BindingFlags.NonPublic | BindingFlags.Instance,这样上例的方法除了输出Func2之外,还会输出下面两个方法。这两个方法是Object类中的protected方法,如果不想获取它们,可以在上面的参数中再添加BindingFlags.DeclaredOnly

-> Finalize
-> MemberwiseClone
(2)反射字段和属性

运行时获取字段和属性的方式跟方法类似,采用GetFileds()函数。GetFileds()方法返回当前 Type的所有公共字段;GetFields(BindingFlags)方法则可以使用指定绑定约束,搜索当前 Type定义的字段, 它们返回的结果都是FieldInfo[]类型。

namespace MyTypeViewer
{
    public class TestClass
    {
        public int field1;
        private string field2;
        protected double field3;
        public string property1 { get; set; }

        public void Func1() { }
        protected void Func2() { }
        private void Func3() { }
    }

class Program
    {
        static void Display(string title, IEnumerable names)
        {
            Console.WriteLine(\"***** {0} *****\", title);
            foreach (var name in names)
            {
                Console.WriteLine(\"-> {0}\", name);
            }
            Console.WriteLine();
        }

        static void ListMethods(Type type)
        {
            var methodNames = from m in type.GetMethods() select m.Name;
            Display(\"Methods\", methodNames);
        }

        static void ListFields(Type type)
        {
            var fieldNames = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(f => f.Name);
            Display(\"Fields\", fieldNames);
        }

        static void ListProperties(Type type)
        {
            var propertyNames = type.GetProperties().Select(f => f.Name);
            Display(\"Properties\", propertyNames);
        }

        static void Main(string[] args)
        {
            ListFields(typeof(TestClass));
        }
    }
}

输出结果:

***** Fields *****
-> field1
-> field2
-> field3
-> k__BackingField

***** Properties *****
-> property1

GetFields()的返回结果中我们可以看到k__BackingField,但是要真正获取property1的话需要采用GetProperties()方法。

(3)反射实现的接口

反射实现的接口也是类似的情况,采用Type类的GetInterfaces()方法,它返回的是Type[]

namespace MyTypeViewer
{
    interface ISampleInterface
    {
        void SampleMethod();
    }

    public class TestClass : ISampleInterface
    {
        void ISampleInterface.SampleMethod()
        {
            Console.WriteLine(\"implement interface member\");
        }
    }

    class Program
    {
        static void Display(string title, IEnumerable names)
        {
            Console.WriteLine(\"***** {0} *****\", title);
            foreach (var name in names)
            {
                Console.WriteLine(\"-> {0}\", name);
            }
            Console.WriteLine();
        }

        static void ListInterfaces(Type type)
        {
            var interfaces = type.GetInterfaces().Select(t => t.Name);
            Display(\"Interfaces\", interfaces);
        }

        static void Main(string[] args)
        {
            ListInterfaces(typeof(TestClass));
        }
    }
}

输出结果:

***** Interfaces *****
-> ISampleInterface
(4)反射泛型类型

上面的例子中我们都采用typeof操作符获取某种类型,对于泛型类型,则必须指定T,如ListMethods(typeof(List));是可以的,但是不能直接使用typeof(List)

另外我们还可以通过Type.GetType(typeName)方法来获取某种类型,如Type t = Type.GetType(\"System.Int32\");。这里必须使用完全限定名,而且要求大小写完全匹配。如果使用\"System.int32\"或者\"Int32\"会找不到我们想要的类型,t为空。

而对于泛型类型,若我们采用上述方法来获取类型,则需要使用反勾号(`)加上数字值的语法来表示类型支持的参数个数。
例如,System.Collections.Generic.List可以写成\"System.Collections.Generic.List`1\";
System.Collections.Generic.Dictionary可以写成\"System.Collections.Generic.Dictionary`2\"

(5)反射方法参数和返回值

上面的所有示例中,我们都只返回了名字,其实我们还可以从MethodInfo或者FieldInfo或者Type中获取更多其他的信息。
下面我们以MethodInfo为例,来丰富上面的ListMethods()方法,除了列出所有方法的名字外,还输出它们的参数(MethodInfo.GetParameters())和返回值(MethodInfo.ReturnType)。

static void ListMethods(Type type)
{
    var methods = type.GetMethods();
    Console.WriteLine(\"***** Methods *****\");
    foreach (var m in methods)
    {
        string retVal = m.ReturnType.FullName;
        var paramInfos = m.GetParameters().Select(p => string.Format(\"{0} {1}\", p.ParameterType, p.Name));
        string paramInfo = String.Join(\", \", paramInfos.ToArray());
        Console.WriteLine(\"-> {0} {1}( {2} )\", retVal, m.Name, paramInfo);
    }
}

输出结果:

***** Methods *****
-> System.String get_property1(  )
-> System.Void set_property1( System.String value )
-> System.String Func1( System.Int32 p1, System.Double p2 )
-> System.String ToString(  )
-> System.Boolean Equals( System.Object obj )
-> System.Int32 GetHashCode(  )
-> System.Type GetType(  )

3. 自定义的元数据查看器有什么用

上面我们通过几个例子可以看到Type类型有很多功能很强大的方法可以查看元数据。那么,查看这些元数据有什么用呢?当你想动态使用这些类型时,它们就变得非常有用了,下面通过几个常用的例子来说明如何使用。

(1)如何动态创建对象

动态创建对象可以使用Assembly.CreateInstance()Activator.CreateInstance()方法。动态创建出来的对象与new创建的对象一样,只是前者不需要在编译前就知道类的名字。

namespace MyTypeViewer
{
    public class TestClass
    {
        public string property1 { get; set; }

        public void Func1() 
        {
            Console.WriteLine(\"Hello World!\");
        }
    }

    public static class ReflectionHelper
    {
        public static T CreateInstance(string assemblyName, string nameSpace, string className)
        {
            try
            {
                string fullName = string.Fortmat(\"{0}.{1}\", nameSpace, className);
                object obj = Assembly.Load(assemblyName).CreateInstance(fullName);
                return (T)obj;
            }
            catch
            {
                return default(T);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var testInstance = ReflectionHelper.CreateInstance(\"MyTypeViewer\", \"MyTypeViewer\", \"TestClass\");
            testInstance.property1 = \"Test Property\";
            testInstance.Func1();
        }
    }
}
(2)如何动态创建委托

CreateDelegate有很多种不同的重载方法,我们这里采用的是用MethodInfo

public static Delegate CreateDelegate(    
        Type type, 
        object firstArgument,    
        MethodInfo method
)

下面的例子来自MSDN

namespace CreateDelegate
{
    class ExampleForm : Form
    {
        public ExampleForm()
            : base()
        {
            this.Text = \"Click me\";
        }
    }

    class Example
    {
        public static void Main()
        {
            Example ex = new Example();
            ex.HookUpDelegate();
        }

        private void HookUpDelegate()
        {
            Assembly assem = typeof(Example).Assembly;

            Type tExForm = assem.GetType(\"CreateDelegate.ExampleForm\");
            Object exFormAsObj = Activator.CreateInstance(tExForm);

            EventInfo evClick = tExForm.GetEvent(\"Click\");
            Type tDelegate = evClick.EventHandlerType;

            MethodInfo miHandler =
                typeof(Example).GetMethod(\"LuckyHandler\",
                    BindingFlags.NonPublic | BindingFlags.Instance);

            Delegate d = Delegate.CreateDelegate(tDelegate, this, miHandler);

            MethodInfo addHandler = evClick.GetAddMethod();
            Object[] addHandlerArgs = { d };
            addHandler.Invoke(exFormAsObj, addHandlerArgs);

            Application.Run((Form)exFormAsObj);
        }

        private void LuckyHandler(Object sender, EventArgs e)
        {
            MessageBox.Show(\"This event handler just happened to be lying around.\");
        }
    }
}

这里我们先动态创建了一个ExampleForm窗体实例,然后取得它上面的Click事件的委托类型tDelegate,再根据该委托类型和我们的LuckyHandler方法创建委托d。最后,运行该程序时会弹出一个窗体,点击任意位置就会调用LuckyHandler方法。

4. 反射的应用实例1

为了更好地理解反射的机制,下面我们通过一个简单的动态加载插件的实例来说明反射的作用。
(1)首先,我们建立一个简单的ClassLibrary来定义我们接下来要用到的插件的接口,编译下面的这个接口我们将得到CommonTypeForPlugIn.dll (里面定义了一个接口IFunctionality和它的一个DoIt()函数,以及一个属性类CompanyInfoAttribute)。

namespace CommonTypeForPlugIn
{
    public interface IFunctionality
    {
        void DoIt();
    }

    [AttributeUsage(AttributeTargets.Class)]
    public sealed class CompanyInfoAttribute : Attribute
    {
        public string CompanyName { get; set; }
        public string CompanyUrl { get; set; }
    }
}

(2)在CommonTypeForPlugIn的基础上实现不同的插件,这里提供了Demo1Demo2

using CommonTypeForPlugIn; // You should add CommonTypeForPlugIn.dll to References first

namespace Demo1
{
    [CompanyInfo(CompanyName = \"Demo1\", CompanyUrl = \"http://demo1.com\")]
    public class Demo1 : IFunctionality
    {
        void IFunctionality.DoIt()
        {
            Console.WriteLine(\"Demo1 is in using now.\");
        }
    }
}
using CommonTypeForPlugIn;

namespace Demo2
{
    [CompanyInfo(CompanyName = \"Demo2\", CompanyUrl = \"http://demo2.com\")]
    public class Demo2 : IFunctionality
    {
        void IFunctionality.DoIt()
        {
            Console.WriteLine(\"Demo2 is in using now.\");
        }
    }
}

(3)接下来我们创建一个应用台程序来实现动态加载上面不同的插件。
PlugInExample类里我们提供了DisplayPlugInsForCommonType()DisplayAndRunPlugIn()两个公共的函数用来分别显示所有的实现CommonType的插件(这里我们上面编译生成的dll都拷贝到这个控制台程序的objd/debug/目录下新建的plugins文件夹下了)和运行一个插件。
DisplayAndRunPlugIn(fileName)函数根据用户输入的插件名去加载那个dll,然后动态给插件里的实现IFunctionality接口的类创建实例,并执行它的DoIt()方法,最后动态获取插件里的CompanyInfoAttribute类,并输出其中的特性值 DisplayCompanyInfo(t)

using System.IO;
using CommonTypeForPlugIn;
using System.Reflection;

namespace LearnCSharp
{
    public class PlugInExample
    {
        public void DisplayPlugInsForCommonType()
        {
            var plugins = ListAllExternalModule();
            if (plugins == null || !plugins.Any())
            {
                Console.WriteLine(\"No plugin provided.\");
            }
            else
            {
                Console.WriteLine(\"List of all plugins:\");
                foreach (var plugin in plugins)
                {
                    Console.WriteLine(Path.GetFileName(plugin));
                }
            }
        }

        public void DisplayAndRunPlugIn(string fileName)
        {
            if (fileName == \"CommonTypeForPlugIn.dll\")
            {
                Console.WriteLine(\"Dll {0} has no plug-in.\", fileName);
            }
            else if (!LoadExternalModule(fileName))
            {
                Console.WriteLine(\"Load Dll {0} failed.\", fileName);
            }
        }

        private IEnumerable ListAllExternalModule()
        {
            var directory = string.Format(\"{0}/plugins/\", Directory.GetCurrentDirectory().TrimEnd(\'/\'));
            return Directory.GetFiles(directory, \"*.dll\");
        }

        private bool LoadExternalModule(string fileName)
        {
            Assembly plugInAsm = null;
            var path = string.Format(\"{0}/plugins/{1}\", Directory.GetCurrentDirectory().TrimEnd(\'/\'), fileName);

            try
            {
                plugInAsm = Assembly.LoadFrom(path);
            }
            catch (Exception ex)
            {
                Console.WriteLine(\"Failed to load assembly {0}, error: {1}\", path, ex.Message);
                return false;
            }

            var classTypes = plugInAsm.GetTypes().Where(t => t.IsClass && t.GetInterface(\"IFunctionality\") != null);
            foreach (Type t in classTypes)
            {
                IFunctionality func = (IFunctionality)plugInAsm.CreateInstance(t.FullName, true);
                func.DoIt();
                DisplayCompanyInfo(t);
            }
            return true;
        }

        private void DisplayCompanyInfo(Type t)
        {
            var companyInfos = t.GetCustomAttributes(false).Where(c => c.GetType() == typeof(CompanyInfoAttribute));
            foreach (CompanyInfoAttribute companyInfo in companyInfos)
            {
                Console.WriteLine(\"CompanyName: {0}, CompanyUrl: {1}\", companyInfo.CompanyName, companyInfo.CompanyUrl);
            }
        }
    }   

    class Program
    {
        static void Main(string[] args)
        {
            var ex = new PlugInExample();
            ex.DisplayPlugInsForCommonType();
            Console.WriteLine(\"Please choose a dll to load:\");
            string fileName = Console.ReadLine();
            ex.DisplayAndRunPlugIn(fileName);
        }
    }
}

输出结果:

List of all plugins:
Demo1.dll
Demo2.dll
Please choose a dll to load:
Demo1.dll
Demo1 is in using now.
CompanyName: Demo1, CompanyUrl: http://demo1.com

参考文献:

  1. .NET Framework 中的反射
  2. C#反射设置属性值和获取属性值
  3. 《精通C#》
  4. C#Reflection学习记录
  5. [整理]C#反射(Reflection)详解
  6. C#反射之创建对象实例
  7. C#高效反射调用方法类

相关内容

热门资讯

500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...
Apache Doris 2.... 亲爱的社区小伙伴们,我们很高兴地向大家宣布,Apache Doris 2.0.0 版本已于...
python清除字符串里非数字... 本文实例讲述了python清除字符串里非数字字符的方法。分享给大家供大家参考。具体如下: impor...