好问题
Good  Question
  • 首 页
  • 问题
    • PHP
    • JAVA
    • CPlusPlus
    • C#
    • SQL
  • 关 于
  • 联 系
C#中使用反射来根据字符串获取属性值 关闭 返回上一级  

C#中使用反射来根据字符串获取属性值
+ 查看更多

发布日期:2018-03-07 14:07
分类:C#
浏览次数:93
我正在尝试使用反射来进行数据转换的示例 (C# Reflection Tips: Data transformation using Reflection, [[http://geekswithblogs.net/shahed/archive/2008/07/24/123998.aspx]] )。
该示例中,GetSourceValue 函数有一个比较各种类型的switch语句,
   private object GetSourceValue(string propertyName) 
    { 
        if (SourceObject == null) 
        { 
            SourceDataProvider provider = new SourceDataProvider(); 
            this.SourceObject = provider.GetSource(); 
        }

        switch (propertyName) 
        { 
            case "FirstName": 
                return SourceObject.FirstName; 
            case "LastName": 
                return SourceObject.LastName; 
            case "ContactAddress": 
                return this.SourceObject.ContactAddress; 
            case "ContactPhone": 
                return this.SourceObject.ContactPhone; 
            case "ContactMobile": 
                return this.SourceObject.ContactMobile; 
            case "ShippingAddress": 
                return this.SourceObject.ShippingAddress; 
            case "ShippingPhone": 
                return this.SourceObject.ShippingPhone; 
            case "ShippingMobile": 
                return this.SourceObject.ShippingMobile; 
            default: 
                return string.Empty; 
        } 
    }
我想删除这些类型和属性,并且 GetSourceValue 函数只使用一个字符串作为参数来获取该属性的值。我想以字符串的形式传递一个类和属性,并获得该类对象的属性值。
这有可能吗?

回答

 public static object GetPropValue(object src, string propName)
 {
     return src.GetType().GetProperty(propName).GetValue(src, null);
 }
当然,你会想添加验证这没什么,但这是它的要点。
上一篇在.NET中通过“String.Format()”方法在千位位置为数字添加逗号
类型检查:使用 typeof, GetType 还是 is ?下一篇
下一篇类型检查:使用 typeof, GetType 还是 is ?

最新文章

  • 函数`__construct`用来干嘛的
    发布日期:2018-03-26
  • 通过访客的IP得到他们的地区
    发布日期:2018-03-26
  • 合并两个PHP对象的最好的方法是什么?
    发布日期:2018-03-26
  • 该如何把一该如何把一个对象转化成数组?
    发布日期:2018-03-26
  • 什么是输出缓冲区?
    发布日期:2018-03-26
  • 在PHP中怎么把用逗号分隔的字符串分隔在一个数组里?
    发布日期:2018-03-26
  • 在PHP中使用foreach循环时查找数组的最后一个元素
    发布日期:2018-03-26
关于好问
收集整理一些有用的问题和回答,造福中国的程序旺和IT喵们!
友情链接
起飞页 
相关信息
版权声明
Copyright © 2016 - 2022  苏州卡达网络科技有限公司 备案号:苏ICP备09008221号