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

using UnityEngine;
using System.Collections;
using System;
using System.Reflection;

public class Test1 : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Test test = new Test();
        test.one = "555";
        test.two = 444;
        test.three = 20;

        print(  GetObjectPropertyValue(test,"three"));
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    public static string GetObjectPropertyValue(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;}

}


你可能感兴趣的:(C#)