什么是编程语言的反射属性? [英] What is Reflection property of a programming language?

查看:88
本文介绍了什么是编程语言的反射属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说大多数高级动态类型语言都是自反的.维基百科上的 Reflection (computer programming) 解释了,但它并没有真正给出清楚地说明它的含义.任何人都可以通过相关示例以更简单的方式解释它吗?

Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?

推荐答案

举个例子,如何实际使用反射:

To give you a example how to use Reflection in a practical way:

假设您正在开发一个应用程序,您希望使用插件扩展该应用程序.这些插件是简单的程序集,只包含一个名为 Person 的类:

Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:

namespace MyObjects
{
    public class Person
    {
        public Person() { ... Logic setting pre and postname ... }
        private string _prename;
        private string _postname;
        public string GetName() { ... concat variabes and return ... }
    }
}

嗯,插件应该在运行时扩展您的应用程序.这意味着,当您的应用程序已经运行时,应该从另一个程序集中加载内容和逻辑.这意味着这些资源不会编译到您的程序集中,即 MyApplication.exe.假设它们位于一个库中:MyObjects.Person.dll.

Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.

您现在面临这样一个事实:您需要提取此信息,例如从 MyObjects.Person 访问 GetName() 函数.

You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.

// Create an assembly object to load our classes
Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + @"MyObjects.Person.dll");
Type objType = testAssembly.GetType("MyObjects.Person");

// Create an instace of MyObjects.Person
var instance = Activator.CreateInstance(objType);

// Call the method
string fullname = (string)calcType.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, instance, null);

如您所见,您可以使用 System.Reflection 在运行时动态加载资源.这可能有助于了解您可以使用它的方式.

As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.

查看此页面,了解如何以更多方式访问程序集的示例细节.和我写的内容基本一样.

Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.

这篇关于什么是编程语言的反射属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆