首页 > 编程语言 > 详细

D语言反射

时间:2016-08-04 06:46:22      阅读:291      评论:0      收藏:0      [点我收藏+]

        静态语言能不能使用反射呢? 在D语言这里可以肯定地告诉你,绝对是可以的。先来看几个程序:

一、反射当然程序中使用到的模块与类型

        ModuleInfo* m1;
        int i1=0;
        foreach (m; ModuleInfo)
        {
            m1 = m;
            writeln(++i1, " modules : ", m1.name);
            TypeInfo_Class[] typeInfos = m1.localClasses;
            int i2=0;
            foreach(typeInfo;typeInfos)
            {
                writeln("  -> ", ++i2 , " Type : ", typeInfo);
            }
        }

技术分享

这是一个让人震惊的结果,模块与类型都显示出来了。

二、使用类型名创建对象

方法一:main.d

import std.stdio;
import std.traits;
import std.format;
import Utils;

class ABC
{
    public void PrintName()
    {
        writeln("Honan!!!");
    }
}

int main(string[] argv)
{
    try
    {
        auto obj = Object.factory("main.ABC");
        writeln(typeid(obj));
        auto a = cast(ABC)obj;
        a.PrintName();
    }
    catch(Throwable e)
    {
        writeln(e.msg);
    }
    readln();
    return 0;
}
技术分享

方法二:main.d

import std.stdio;
import std.traits;
import std.format;
import Utils;

class ABC
{
    public void PrintName()
    {
        writeln("Honan!!!");
    }
}

int main(string[] argv)
{
    try
    {
        auto typeInfo = TypeInfo_Class.find("main.ABC");
        auto obj = typeInfo.create();
        writeln(typeid(obj));
        auto a = cast(ABC)obj;
        a.PrintName();
    }
    catch(Throwable e)
    {
        writeln(e.msg);
    }
    readln();
    return 0;
}

技术分享

 

 

作者:宛宏南

D语言反射

原文:http://www.cnblogs.com/wanhongnan/p/5735217.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!