Chinaunix首页 | 论坛 | 博客
  • 博客访问: 567722
  • 博文数量: 208
  • 博客积分: 3286
  • 博客等级: 中校
  • 技术积分: 1780
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-24 20:38
文章分类

全部博文(208)

文章存档

2012年(7)

2011年(28)

2010年(21)

2009年(76)

2008年(65)

2007年(11)

我的朋友

分类: C/C++

2007-11-27 15:50:25


// --------------------------------------------------------
// 作者:李剑 msn:newshadowk@hotmail.com qq:50248291
// --------------------------------------------------------
using System;
using System.Threading;
using System.Reflection;
using System.Collections.Generic;

class ClassHelperDemo
{
    
public static void Main()
    
{
        
#region 演示一:动态生成类。
        
//生成一个类t。
        Type t = ClassHelper.BuildType("MyClass");
        
#endregion


        
#region 演示二:动态添加属性到类。
        
//先定义两个属性。
        List<ClassHelper.CustPropertyInfo> lcpi = new List<ClassHelper.CustPropertyInfo>();
        ClassHelper.CustPropertyInfo cpi;

        cpi 
= new ClassHelper.CustPropertyInfo("System.String""S1");
        lcpi.Add(cpi);
        cpi 
= new ClassHelper.CustPropertyInfo("System.String""S2");
        lcpi.Add(cpi);



        
//再加入上面定义的两个属性到我们生成的类t。
        t = ClassHelper.AddProperty(t, lcpi);

        
//把它显示出来。
        DispProperty(t);

        
//再定义两个属性。
        lcpi.Clear();
        cpi 
= new ClassHelper.CustPropertyInfo("System.Int32""I1");
        lcpi.Add(cpi);
        cpi 
= new ClassHelper.CustPropertyInfo("System.Int32""I2");
        lcpi.Add(cpi);

        
//再加入上面定义的两个属性到我们生成的类t。
        t = ClassHelper.AddProperty(t, lcpi);

        
//再把它显示出来,看看有没有增加到4个属性。
        DispProperty(t);
        
#endregion


        
#region 演示三:动态从类里删除属性。
        
//把'S1'属性从类t中删除。
        t = ClassHelper.DeleteProperty(t, "S1");
        
//显示出来,可以看到'S1'不见了。
        DispProperty(t);

        
#endregion

        
        
#region 演示四:动态获取和设置属性值。
        
//先生成一个类t的实例o。
        object o = ClassHelper.CreateInstance(t);

        
//给S2,I2属性赋值。
        ClassHelper.SetPropertyValue(o, "S2""abcd");
        ClassHelper.SetPropertyValue(o, 
"I2"1234);

        
//再把S2,I2的属性值显示出来。
        Console.WriteLine("S2 = {0}", ClassHelper.GetPropertyValue(o, "S2"));
        Console.WriteLine(
"I2 = {0}", ClassHelper.GetPropertyValue(o, "I2"));
        
#endregion


        Console.Read();
    }


    
public static void DispProperty(Type t)
    
{
        Console.WriteLine(
"ClassName '{0}'", t.Name);
        
foreach (PropertyInfo pInfo in t.GetProperties())
        
{
            Console.WriteLine(
"Has Property '{0}'", pInfo.ToString());
        }

        Console.WriteLine(
"");
    }

}


 

输出:

ClassName 'MyClass'
Has Property 'System.String S1'
Has Property 'System.String S2'

ClassName 'MyClass'
Has Property 'Int32 I1'
Has Property 'Int32 I2'
Has Property 'System.String S1'
Has Property 'System.String S2'

ClassName 'MyClass'
Has Property 'Int32 I1'
Has Property 'Int32 I2'
Has Property 'System.String S2'

S2 = abcd
I2 = 1234


阅读(1042) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~