C# 反射属性值和遍历属性名

来源:互联网 发布:棉麻旗袍 知乎专栏 编辑:程序博客网 时间:2024/05/22 05:22
using UnityEngine;using System.Collections;using System;using System.Reflection;public class Test1 : MonoBehaviour {// Use this for initializationvoid Start () {        Test test = new Test();        test.one = "555";        test.two = 444;        test.three = 20;        print(  GetObjectPropertyValue<Test>(test,"three"));}// Update is called once per framevoid Update () {}    public static string GetObjectPropertyValue<T>(T t, string propertyname)    {        Type type = typeof(T);        //获取所有属性名        //PropertyInfo[] pInfos = type.GetProperties();        //for (int i = 0; i < pInfos.Length; i++)        //{        //    Debug.Log("属性名:"+pInfos[i].Name);        //}        //end        PropertyInfo property = type.GetProperty(propertyname);        Debug.Log(property);        if (property == null) return string.Empty;        object o = property.GetValue(t, null);        if (o == null) return string.Empty;        return o.ToString();    }}



必须得写get;set;

using UnityEngine;using System.Collections;public class Test  {    private string _one;    public string one    {        get { return _one; }        set { _one = value; }    }    private int _two;    public int two    {        get { return _two; }        set { _two = value; }    }    public int three{get;set;}}


0 0
原创粉丝点击