码迷,mamicode.com
首页 > Windows程序 > 详细

C# 字符串访问属性

时间:2019-11-15 11:54:07      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:bug   this   oat   tty   ret   字符串   setvalue   his   tor   

//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

C# 字符串访问属性

标签:bug   this   oat   tty   ret   字符串   setvalue   his   tor   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!