本文共 2210 字,大约阅读时间需要 7 分钟。
using System;
using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication33 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Values item = SetValues(); PrintValues(item); } /// <summary> /// 通过遍历属性输出属性和值 /// </summary> /// <param name="item"></param> private void PrintValues(Values item) { System.Reflection.PropertyInfo[] properties = item.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo property in properties) { string name=property.Name; string value = property.GetValue(item).ToString(); } } /// <summary> /// 通过遍历属性赋值 /// </summary> /// <returns></returns> private Values SetValues() { Values item = new Values(); System.Reflection.PropertyInfo[] properties = item.GetType().GetProperties(); for (int i = 0; i < properties.Length; i++) { properties[i].SetValue(item, (i + 1)); } return item; } } class Values { public int Value1 { get; set; } public int Value2 { get; set; } public int Value3 { get; set; } public int Value4 { get; set; } public int Value5 { get; set; } public int Value6 { get; set; } public int Value7 { get; set; } public int Value8 { get; set; } public int Value9 { get; set; } public int Value10 { get; set; } } }————————————————
public class PP 2 { 3 public string a { get; set; } 4 public string b { get; set; } 5 public string c { get; set; } 6 } 7 class Program 8 { 9 static void Main(string[] args)10 {11 Hashtable ht = new Hashtable();12 13 14 ht.Add("a", "utf8");15 ht.Add("b", "xxxx");16 ht.Add("c", "xxxx");17 PP config = new PP();18 PropertyInfo[] propertys = config.GetType().GetProperties();19 foreach (PropertyInfo property in propertys)20 {21 for (int i = 0; i < ht.Count; i++)22 {23 property.SetValue(config, ht[property.Name].ToString(), null);24 }25 }26 Console.WriteLine(config.a+"\t"+config.b);27 Console.ReadLine();28 }29 }
转载地址:http://owlws.baihongyu.com/