| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1447 人关注过本帖
标题:Type.GetField()通过变量名来得到变量
只看楼主 加入收藏
qubo1982
Rank: 9Rank: 9Rank: 9
等 级:蜘蛛侠
威 望:1
帖 子:367
专家分:1132
注 册:2009-3-18
结帖率:100%
收藏
 问题点数:0 回复次数:0 
Type.GetField()通过变量名来得到变量
程序代码:
class Program
{
    static void Main(string[] args)
    {
        Temp t = new Temp()
        {
            Age = 11, Id = "2", Name = "AA"
                                   };
        string name = t.GetValueByType("name"); //这里对应TEMP类的string name
        string id = t.GetValueByType("id");
        Console.WriteLine("{0},{1}", name, id);
    }
}

class Temp
{
    public string GetValueByType(string type)
    {
        FieldInfo fi = this.GetType().GetField(type,  BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.NonPublic);
        if (fi == null)
            return "";
        else
            return (string)fi.GetValue(this);
    }
    string name = "", id = "";
    int age = 0;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public string Id
    {
        get { return id; }
        set { id = value; }
    }
} 

2011-11-01 18:21
快速回复:Type.GetField()通过变量名来得到变量
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011575 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved