C# 字符串访问属性

//1.公开字段的实现
public class Foo{
	public float aa=100;
	public void test(){
		this["aa"]=300;
	}
	public float this[string name]{
		get{
			return (float)GetType().GetField(name).GetValue(this);
		}
		set{
			GetType().GetField(name).SetValue(this,value);
		}
	}
}
//2.私有属性的实现
public class Foo{
	private float m_aa=100;
	public float aa{ get=>m_aa; set=>m_aa=value;}
	public void test(){
		this["aa"]=300;
	}
	public float this[string name]{
		get{
			return (float)GetType().GetProperty(name).GetValue(this);
		}
		set{
			GetType().GetProperty(name).SetValue(this,value);
		}
	}
}

var v=new Vector2(10,20);
Debug.Log(v.GetType().GetField("x").GetValue(v));//output:10
Debug.Log(v.GetType().GetField("y").GetValue(v));//output:20

var foo=new Foo();
Debug.Log(foo["aa"]);//output:100
foo["aa"]=200;
Debug.Log(foo["aa"]);//output:200
foo.test();
Debug.Log(foo["aa"]);//output:300


原文地址:https://www.cnblogs.com/kingBook/p/11865149.html