.Net反射的巧妙用法

在.Net中,通过反射,给对象属性利用foreach赋值

class Program
    
{
        
static void Main(string[] args)
        
{
            Type type 
= typeof(Worker);
            Worker worker 
= new Worker();
            
foreach (PropertyInfo proInfo in type.GetProperties())
            
{
                Console.WriteLine(proInfo.Name);
                Console.WriteLine(proInfo.ToString());
                proInfo.SetValue(worker, 
"ss"null);
            }

            Console.WriteLine(
"Worker.Name:{0}", worker.Name);
            Console.Read();
        }

    }
 
    
public class Worker
    
{
        
private string _name;
        
public string Name
        
{
            
get return _name; }
            
set { _name = value; }
        }


        
private string _sex;
        
public string Sex
        
{
            
get return _sex; }
            
set { _sex = value; }
        }

    }


小技巧:当你写出private string _name;后 按ctrl+r+e(先r再e) 即可生成public string Name的内容了!

posted on 2008-04-03 19:50  eoiioe  阅读(306)  评论(0编辑  收藏  举报

导航