Chinaunix首页 | 论坛 | 博客
  • 博客访问: 571826
  • 博文数量: 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:49:34

写的一个类帮助器,思路是,可以使用这个帮助器对类动态地控制(在运行时),如添加,删除其成员。

最近要用到这个,在网上找了点资料,也不全面,就自己查msdn帮助文件。自己写了一个,功能还不是很完善,如果大家有兴趣扩展下功能的话,就再好不过了。现在只能控制属性,还不能控制其它成员,如事件,方法等等。

演示一:动态生成类。
演示二:动态添加属性到类。
演示三:动态从类里删除属性。
演示四:动态获取和设置属性值。

类帮助器代码:


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

/// 
/// 类帮助器,可以动态对类,类成员进行控制(添加,删除),目前只支持属性控制。
/// 注意,属性以外的其它成员会被清空,功能还有待完善,使其不影响其它成员。
/// 

public class ClassHelper
{
    
#region 公有方法
    
/// 
    
/// 根据类的类型型创建类实例。
    
/// 

    
/// 将要创建的类型。
    
/// 返回创建的类实例。

    public static object CreateInstance(Type t)
    
{
        
return Activator.CreateInstance(t);
    }


    
/// 
    
/// 根据类的名称,属性列表创建型实例。
    
/// 

    
/// 将要创建的类的名称。
    
/// 将要创建的类的属性列表。
    
/// 返回创建的类实例

    public static object CreateInstance(string className, List<CustPropertyInfo> lcpi)
    
{
        Type t 
= BuildType(className);
        t 
= AddProperty(t, lcpi);
        
return Activator.CreateInstance(t);
    }


    
/// 
    
/// 根据属性列表创建类的实例,默认类名为DefaultClass,由于生成的类不是强类型,所以类名可以忽略。
    
/// 

    
/// 将要创建的类的属性列表
    
/// 返回创建的类的实例。

    public static object CreateInstance(List<CustPropertyInfo> lcpi)
    
{
        
return CreateInstance("DefaultClass", lcpi);
    }


    
/// 
    
/// 根据类的实例设置类的属性。
    
/// 

    
/// 将要设置的类的实例。
    
/// 将要设置属性名。
    
/// 将要设置属性值。

    public static void SetPropertyValue(object classInstance, string propertyName, object propertSetValue)
    
{
        classInstance.GetType().InvokeMember(propertyName, BindingFlags.SetProperty,
                                      
null, classInstance, new object[] { Convert.ChangeType(propertSetValue, propertSetValue.GetType()) });
    }


    
/// 
    
/// 根据类的实例获取类的属性。
    
/// 

    
/// 将要获取的类的实例
    
/// 将要设置的属性名。
    
/// 返回获取的类的属性。

    public static object GetPropertyValue(object classInstance, string propertyName)
    
{
        
return classInstance.GetType().InvokeMember(propertyName, BindingFlags.GetProperty,
                                                      
null, classInstance, new object[] { });
    }


    
/// 
    
/// 创建一个没有成员的类型的实例,类名为"DefaultClass"。
    
/// 

    
/// 返回创建的类型的实例。

    public static Type BuildType()
    
{
        
return BuildType("DefaultClass");
    }


    
/// 
    
/// 根据类名创建一个没有成员的类型的实例。
    
/// 

    
/// 将要创建的类型的实例的类名。
    
/// 返回创建的类型的实例。

    public static Type BuildType(string className)
    
{

        AppDomain myDomain 
= Thread.GetDomain();
        AssemblyName myAsmName 
= new AssemblyName();
        myAsmName.Name 
= "MyDynamicAssembly";

        
//创建一个永久程序集,设置为AssemblyBuilderAccess.RunAndSave。
        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName,
                                                        AssemblyBuilderAccess.RunAndSave);

        
//创建一个永久单模程序块。
        ModuleBuilder myModBuilder =
            myAsmBuilder.DefineDynamicModule(myAsmName.Name, myAsmName.Name 
+ ".dll");
        
//创建TypeBuilder。
        TypeBuilder myTypeBuilder = myModBuilder.DefineType(className,
                                                        TypeAttributes.Public);

        
//创建类型。
        Type retval = myTypeBuilder.CreateType();

        
//保存程序集,以便可以被Ildasm.exe解析,或被测试程序引用。
        myAsmBuilder.Save(myAsmName.Name + ".dll");
        
return retval;
    }


    
/// 
    
/// 添加属性到类型的实例,注意:该操作会将其它成员清除掉,其功能有待完善。
    
/// 

    
/// 指定类型的实例。
    
/// 表示属性的一个列表。
    
/// 返回处理过的类型的实例。

    public static Type AddProperty(Type classType, List<CustPropertyInfo> lcpi)
    
{
        
//合并先前的属性,以便一起在下一步进行处理。
        MergeProperty(classType, lcpi);
        
//把属性加入到Type。
        return AddPropertyToType(classType, lcpi);
    }


    
/// 
    
/// 添加属性到类型的实例,注意:该操作会将其它成员清除掉,其功能有待完善。
    
/// 

    
/// 指定类型的实例。
    
/// 表示一个属性。
    
/// 返回处理过的类型的实例。

    public static Type AddProperty(Type classType, CustPropertyInfo cpi)
    
{
        List
<CustPropertyInfo> lcpi = new List<CustPropertyInfo>();
        lcpi.Add(cpi);
        
//合并先前的属性,以便一起在下一步进行处理。
        MergeProperty(classType, lcpi);
        
//把属性加入到Type。
        return AddPropertyToType(classType, lcpi);
    }


    
/// 
    
/// 从类型的实例中移除属性,注意:该操作会将其它成员清除掉,其功能有待完善。
    
/// 

    
/// 指定类型的实例。
    
/// 要移除的属性。
    
/// 返回处理过的类型的实例。

    public static Type DeleteProperty(Type classType, string propertyName)
    
{
        List
<string> ls = new List<string>();
        ls.Add(propertyName);

        
//合并先前的属性,以便一起在下一步进行处理。
        List<CustPropertyInfo> lcpi = SeparateProperty(classType, ls);
        
//把属性加入到Type。
        return AddPropertyToType(classType, lcpi);
    }


    
/// 
    
/// 从类型的实例中移除属性,注意:该操作会将其它成员清除掉,其功能有待完善。
    
/// 

    
/// 指定类型的实例。
    
/// 要移除的属性列表。
    
/// 返回处理过的类型的实例。

    public static Type DeleteProperty(Type classType, List<string> ls)
    
{
        
//合并先前的属性,以便一起在下一步进行处理。
        List<CustPropertyInfo> lcpi = SeparateProperty(classType, ls);
        
//把属性加入到Type。
        return AddPropertyToType(classType, lcpi);
    }

    
#endregion


    
#region 私有方法
    
/// 
    
/// 把类型的实例t和lcpi参数里的属性进行合并。
    
/// 

    
/// 实例t
    
/// 里面包含属性列表的信息。

    private static void MergeProperty(Type t, List<CustPropertyInfo> lcpi)
    
{
        CustPropertyInfo cpi;
        
foreach (PropertyInfo pi in t.GetProperties())
        
{
            cpi 
= new CustPropertyInfo(pi.PropertyType.FullName, pi.Name);
            lcpi.Add(cpi);
        }

    }


    
/// 
    
/// 从类型的实例t的属性移除属性列表lcpi,返回的新属性列表在lcpi中。
    
/// 

    
/// 类型的实例t。
    
/// 要移除的属性列表。

    private static List<CustPropertyInfo> SeparateProperty(Type t, List<string> ls)
    
{
        List
<CustPropertyInfo> ret = new List<CustPropertyInfo>();
        CustPropertyInfo cpi;
        
foreach (PropertyInfo pi in t.GetProperties())
        
{
            
foreach (string s in ls)
            
{
                
if (pi.Name != s)
                
{
                    cpi 
= new CustPropertyInfo(pi.PropertyType.FullName, pi.Name);
                    ret.Add(cpi);
                }

            }

        }


        
return ret;
    }


    
/// 
    
/// 把lcpi参数里的属性加入到myTypeBuilder中。注意:该操作会将其它成员清除掉,其功能有待完善。
    
/// 

    
/// 类型构造器的实例。
    
/// 里面包含属性列表的信息。

    private static void AddPropertyToTypeBuilder(TypeBuilder myTypeBuilder, List<CustPropertyInfo> lcpi)
    
{
        FieldBuilder customerNameBldr;
        PropertyBuilder custNamePropBldr;
        MethodBuilder custNameGetPropMthdBldr;
        MethodBuilder custNameSetPropMthdBldr;
        MethodAttributes getSetAttr;
        ILGenerator custNameGetIL;
        ILGenerator custNameSetIL;

        
// 属性Set和Get方法要一个专门的属性。这里设置为Public。
        getSetAttr =
            MethodAttributes.Public 
| MethodAttributes.SpecialName |
                MethodAttributes.HideBySig;

        
// 添加属性到myTypeBuilder。
        foreach (CustPropertyInfo cpi in lcpi)
        
{
            
//定义字段。
            customerNameBldr = myTypeBuilder.DefineField(cpi.FieldName,
                                                             Type.GetType(cpi.Type),
                                                             FieldAttributes.Private);

            
//定义属性。
            
//最后一个参数为null,因为属性没有参数。
            custNamePropBldr = myTypeBuilder.DefineProperty(cpi.PropertyName,
                                                             PropertyAttributes.HasDefault,
                                                             Type.GetType(cpi.Type),
                                                             
null);


            
//定义Get方法。
            custNameGetPropMthdBldr =
                myTypeBuilder.DefineMethod(cpi.GetPropertyMethodName,
                                           getSetAttr,
                                           Type.GetType(cpi.Type),
                                           Type.EmptyTypes);

            custNameGetIL 
= custNameGetPropMthdBldr.GetILGenerator();

            custNameGetIL.Emit(OpCodes.Ldarg_0);
            custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
            custNameGetIL.Emit(OpCodes.Ret);

            
//定义Set方法。
            custNameSetPropMthdBldr =
                myTypeBuilder.DefineMethod(cpi.SetPropertyMethodName,
                                           getSetAttr,
                                           
null,
                                           
new Type[] { Type.GetType(cpi.Type) });

            custNameSetIL 
= custNameSetPropMthdBldr.GetILGenerator();

            custNameSetIL.Emit(OpCodes.Ldarg_0);
            custNameSetIL.Emit(OpCodes.Ldarg_1);
            custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
            custNameSetIL.Emit(OpCodes.Ret);

            
//把创建的两个方法(Get,Set)加入到PropertyBuilder中。
            custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
            custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);
        }

    }


    
/// 
    
/// 把属性加入到类型的实例。
    
/// 

    
/// 类型的实例。
    
/// 要加入的属性列表。
    
/// 返回处理过的类型的实例。

    public static Type AddPropertyToType(Type classType, List<CustPropertyInfo> lcpi)
    
{
        AppDomain myDomain 
= Thread.GetDomain();
        AssemblyName myAsmName 
= new AssemblyName();
        myAsmName.Name 
= "MyDynamicAssembly";

        
//创建一个永久程序集,设置为AssemblyBuilderAccess.RunAndSave。
        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName,
                                                        AssemblyBuilderAccess.RunAndSave);

        
//创建一个永久单模程序块。
        ModuleBuilder myModBuilder =
            myAsmBuilder.DefineDynamicModule(myAsmName.Name, myAsmName.Name 
+ ".dll");
        
//创建TypeBuilder。
        TypeBuilder myTypeBuilder = myModBuilder.DefineType(classType.FullName,
                                                        TypeAttributes.Public);

        
//把lcpi中定义的属性加入到TypeBuilder。将清空其它的成员。其功能有待扩展,使其不影响其它成员。
        AddPropertyToTypeBuilder(myTypeBuilder, lcpi);

        
//创建类型。
        Type retval = myTypeBuilder.CreateType();

        
//保存程序集,以便可以被Ildasm.exe解析,或被测试程序引用。
        myAsmBuilder.Save(myAsmName.Name + ".dll");
        
return retval;
    }

    
#endregion


    
#region 辅助类
    
/// 
    
/// 自定义的属性信息类型。
    
/// 

    public class CustPropertyInfo
    
{
        
private string propertyName;
        
private string type;

        
/// 
        
/// 空构造。
        
/// 

        public CustPropertyInfo() { }

        
/// 
        
/// 根据属性类型名称,属性名称构造实例。
        
/// 

        
/// 属性类型名称。
        
/// 属性名称。

        public CustPropertyInfo(string type, string propertyName)
        
{
            
this.type = type;
            
this.propertyName = propertyName;
        }


        
/// 
        
/// 获取或设置属性类型名称。
        
/// 

        public string Type
        
{
            
get return type; }
            
set { type = value; }
        }


        
/// 
        
/// 获取或设置属性名称。
        
/// 

        public string PropertyName
        
{
            
get return propertyName; }
            
set { propertyName = value; }
        }


        
/// 
        
/// 获取属性字段名称。
        
/// 

        public string FieldName
        
{
            
get return propertyName.Substring(01).ToLower() + propertyName.Substring(1); }
        }


        
/// 
        
/// 获取属性在IL中的Set方法名。
        
/// 

        public string SetPropertyMethodName
        
{
            
get return "set_" + PropertyName; }
        }


        
/// 
        
///  获取属性在IL中的Get方法名。
        
/// 

        public string GetPropertyMethodName
        
{
            
get return "get_" + PropertyName; }
        }

    }

    
#endregion

}


 

 显示程序代码

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