(论坛答疑点滴)如何动态设定类的属性和字段?

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

正好有人问这个,代码非常简单,最基本的应用,直接贴代码

using System;

namespace Test

{

/**//// <summary>

/// Class1 的摘要说明。

/// </summary>

class Class1

{

/**//// <summary>

/// 应用程序的主入口点。

/// </summary>

[STAThread]

static void Main(string[] args)

{

//

// TODO: 在此处添加代码以启动应用程序

//

MyFieldClass dv=new MyFieldClass();

System.Collections.Hashtable ht1=new System.Collections.Hashtable();

ht1.Add("FieldA","A");

ht1.Add("FieldC","C");

SetField1(ht1,dv);//如果类中的字段匹配Hashtable中的Key则重新设定

//SetField2(ht1,dv)//如果Hashtable中的Key匹配类中的字段则重新设定,效果等同于SetField1

Console.WriteLine(dv.FieldA);//A

Console.WriteLine(dv.FieldB);//bb

Console.WriteLine(dv.FieldC);//C

System.Collections.Hashtable ht2=new System.Collections.Hashtable();

ht2.Add("PropertyB","b");

ht2.Add("PropertyC","c");

SetProperty1(ht2,dv);//如果类中的属性匹配Hashtable中的Key则重新设定

//SetProperty2(ht2,dv);//如果Hashtable中的Key匹配类中的属性则重新设定,效果等同于SetProperty1

Console.WriteLine(dv.FieldA);//A

Console.WriteLine(dv.FieldB);//b

Console.WriteLine(dv.FieldC);//c

}

public static void SetProperty1(System.Collections.Hashtable ht1,MyFieldClass dv)

{

foreach(System.Collections.DictionaryEntry de in ht1)

{

System.Reflection.PropertyInfo pi=dv.GetType().GetProperty(de.Key.ToString());

if(pi!=null)pi.SetValue(dv,de.Value.ToString(),null);

}

}

public static void SetProperty2(System.Collections.Hashtable ht1,MyFieldClass dv)

{

foreach(System.Reflection.PropertyInfo pi in dv.GetType().GetProperties())

{

if(ht1.Contains(pi.Name))pi.SetValue(dv,ht1[pi.Name],null);

}

}

public static void SetField1(System.Collections.Hashtable ht2,MyFieldClass dv)

{

foreach(System.Collections.DictionaryEntry de in ht2)

{

System.Reflection.FieldInfo fi=dv.GetType().GetField(de.Key.ToString());

if(fi!=null)fi.SetValue(dv,de.Value.ToString());

}

}

public static void SetField2(System.Collections.Hashtable ht2,MyFieldClass dv)

{

foreach(System.Reflection.FieldInfo fi in dv.GetType().GetFields())

{

if(ht2.Contains(fi.Name))fi.SetValue(dv,ht2[fi.Name]);

}

}

}

public class MyFieldClass

{

public string FieldA="aa";

public string FieldB="bb";

public string FieldC="cc";

public string PropertyA

{

get

{

return FieldA;

}

set

{

FieldA=value;

}

}

public string PropertyB

{

get

{

return FieldB;

}

set

{

FieldB=value;

}

}

public string PropertyC

{

get

{

return FieldC;

}

set

{

FieldC=value;

}

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航