Click here to Skip to main content
15,885,920 members
Articles / Programming Languages / C#

Use .NET Reflection APIs to facilitate get/set property

Rate me:
Please Sign up or sign in to vote.
2.63/5 (10 votes)
13 Jan 20051 min read 42.8K   488   12  
Dynamic access to .NET object's property/field.
using System;
using System.Collections;

using NUnit.Framework;
using First.Commons.Property;

namespace First.Test.Property
{
	/// <summary>
	/// DictionaryTest ��ժҪ˵����
	/// </summary>
	[TestFixture] 
	public class DictionaryTest
	{
		public DictionaryTest()
		{
			//
			// TODO: �ڴ˴���ӹ��캯���߼�
			//
		}
		#region SetUp & TearDown

		/// <summary>
		/// SetUp
		/// </summary>
		[SetUp] 
		public void SetUp() 
		{
		}


		/// <summary>
		/// TearDown
		/// </summary>
		[TearDown] 
		public void Dispose()
		{ 
		} 

		#endregion

		#region Tests
		[Test]
		public void TestReadProperty()
		{
			Hashtable map = new Hashtable();
			map.Add("first",GetNewEmployee("id001"));
			map.Add("second",GetNewEmployee("id002"));
			map.Add("three",GetNewEmployee("id003"));

		
			Assert.AreEqual("id001",DynaAccessUtils.GetProperty(map,"first.Emp_id"));
			Assert.AreEqual("id002",DynaAccessUtils.GetProperty(map,"second.Emp_id"));
			Assert.AreEqual("id003",DynaAccessUtils.GetProperty(map,"three.Emp_id"));
		}

		[Test]
		public void TestWriteProperty()
		{
			Hashtable map = new Hashtable();
			map.Add("first",GetNewEmployee("id001"));
			map.Add("second",GetNewEmployee("id002"));
			map.Add("three",GetNewEmployee("id003"));

		
			DynaAccessUtils.SetProperty(map,"first.Emp_id","new001");
			DynaAccessUtils.SetProperty(map,"second.Emp_id","new002");
			DynaAccessUtils.SetProperty(map,"three.Emp_id","new003");

			Assert.AreEqual("new001",((EmployeeInfo)map["first"]).Emp_id);
			Assert.AreEqual("new002",((EmployeeInfo)map["second"]).Emp_id);
			Assert.AreEqual("new003",((EmployeeInfo)map["three"]).Emp_id);
		}

		#endregion

		private EmployeeInfo GetNewEmployee(string emp_id)
		{
			EmployeeInfo emp= new EmployeeInfo();
			emp.Emp_id = emp_id;
			emp.Fname = "cao";
			emp.Hire_date = new DateTime(2004,12,30);
			emp.Job_id = 200;
			emp.Job_lvl =10;
			emp.Lname = "ju";
			emp.Minit = "Minit";
			emp.Pub_id = "pubid";
			return emp;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
China China
developer located in Tianjin, China.interests include C++/.NET/Java, etc. like coding.

Comments and Discussions