asp.net c# Design Pattern WebService Windows Report Control Mobile Symbin Windows Phone 7 Visual Studio 2011

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

Posted on 2007-02-13 22:53  笑缘  阅读(1063)  评论(0)    收藏  举报

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

        
//...
}

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3

asp.net c# Design Pattern WebService Windows Report Control Mobile Windows Phone Visual Studio
asp.net c# Design Pattern WebService Windows Report Control Mobile