c#反射无法获取值 [英] c# reflection can't get values

查看:193
本文介绍了c#反射无法获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程:

 public class Test1 {
public string age {get;组; }
public int?距离{get;组; }
}

我想循环遍历属性和值,但我只得到名称:

 Test1 t = new Test1(); 
t.age =" 333" ;;
t.distance = 4;

PropertyInfo [] props = t.GetType()。GetProperties();
foreach(道具中的PropertyInfo obj)
{
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(obj.Name);
如果(info == null)继续;

object obj2 = info.GetValue(obj,null);
}




我看到属性名称但不是值,我做错了什么?


解决方案

您使用的是错误的对象。你得到的类型是Test1。然后,您开始枚举其属性。但是,如果出现问题,那么您将获取obj的类型(这是PropertyInfo实例),因此类型(在循环内)是PropertyInfo。
然后你试图找到属性(在Test1上)但是使用PropertyInfo类型。

 var t = new Test1(){age =" 333",距离= 4}; 

var props = t.GetType()。GetProperties();
foreach(道具中的var prop)
{
//获取值
var propValue = prop.GetValue(t);
};

在这里使用有意义的变量名称将使您的代码更具可读性并使其明显出现问题。


I have a class :

public class Test1    {
               public string age { get; set; }
           public int? distance { get; set; }
       }

I want to loop over the property and values, but I get only the names :

Test1 t=new Test1();
t.age="333";
t.distance=4;

PropertyInfo[] props = t.GetType().GetProperties();
foreach (PropertyInfo obj in props)
{
Type type = obj.GetType();
                                                                              PropertyInfo info = type.GetProperty(obj.Name);
                                        if (info == null) continue; 

                                        object obj2 = info.GetValue(obj, null);
}


I see the property name but not the value, what do I do wrong?

解决方案

You're using the wrong object. You get the type of t which would be Test1. You then start enumerating its properties. But where things go wrong is that you then fetch the type of obj (which is the PropertyInfo instance) so type (inside the loop) is PropertyInfo. Then you are trying to find the property (on Test1) but using the PropertyInfo type.

var t = new Test1() { age = "333", distance = 4 };

var props = t.GetType().GetProperties();
foreach (var prop in props)
{
   //Get the value
   var propValue = prop.GetValue(t);
};

Using meaningful variable names here will make your code a lot more readable and make it obvious what is going wrong.


这篇关于c#反射无法获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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