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

来源:互联网 发布:优化方案系列丛书 编辑:程序博客网 时间:2024/04/29 16:25

如果我有一个拥有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;
        }

        
//...
}