在C#中怎么通过类名访问类的属性

    技术2022-05-11  88

    如果我有一个拥有FirstName的属性的类Perso,我能通过如下方式访问:Person.FirstName = "Mike";

    能通过下面的方式来访问吗Person["FirstName"]="Mike";

    通过反射类来实现,但是这种方法性能比较低。

    publci  class  YourClass {      //...      public object this[string name]        {            get            {                                  PropertyInfo info = this.PropertyInfoByName(name);                 return info.GetValue(this,null);            }            set            {                               PropertyInfo info = this.PropertyInfoByName(name);                info.SetValue(this,value,null);            }        }        private PropertyInfo PropertyInfoByName(string name)        {            Type type = this.GetType();            PropertyInfo info = type.GetProperty(name);            if (info == null)            {                throw new Exception(String.Format("对象{0}的属性{1}不能被访问 .", type.FullName, name));            }            return info;        }        //...}

     


    最新回复(0)