How to access and invoke private methods,fields or properties

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTe
{
	/// <summary>
	/// Holds blog information
	/// </summary>
	public class Blog
	{
		/// <summary>
		/// Gets the posts count.
		/// </summary>
		private static int PostsCount
		{
			get
			{
				return 10000;
			}
		}

		/// <summary>
		/// Gets the description.
		/// </summary>
		/// <returns></returns>
		private string GetDescription()
		{
			return @"A weblog dedicated to obsessively profiling
reviewing new Internet products and companies";
		}


		/// <summary>
		/// Changes the name of the blog.
		/// </summary>
		/// <param name="newName">The new name.</param>
		private string ChangeBlogName(string newName)
		{
			name = newName;
			return name;
		}


		string url = "http://techcrunch.com";
		string name = "Tech Crunch";
	}
	class Program
	{
		static void Main(string[] args)
		{



			Blog blog = new Blog();
			Type type = typeof(Blog);
			//create reflection bindings - will be used to retrive private fields,methods or properties
			BindingFlags privateBindings = BindingFlags.NonPublic | BindingFlags.Instance;

			// retrive private fields from our class
			FieldInfo[] fieldInfos = type.GetFields(privateBindings);

			// retrive private fields metadata
			foreach (FieldInfo fieldInfo in fieldInfos)
			{
				Console.WriteLine(fieldInfo.Name + " " + fieldInfo.GetValue(blog));
			}


			PropertyInfo[] propertyInfos = type.GetProperties(privateBindings | BindingFlags.Static);
			// retrive private static properties metadata
			foreach (PropertyInfo propertyInfo in propertyInfos)
			{
				// note that no instance need for static property to retrive it's value
				Console.WriteLine(propertyInfo.Name + " " + propertyInfo.GetValue(null, null));
			}

			// call method using MethodInfo object
			MethodInfo miGetDescription = type.GetMethod("GetDescription", privateBindings);
			object retObj = miGetDescription.Invoke(blog, new object[] { });
			Console.WriteLine(retObj);

			// call method using MethodInfo object with input parameters
			MethodInfo miChangeBlogName = type.GetMethod("ChangeBlogName", privateBindings);
			retObj = miChangeBlogName.Invoke(blog, new object[] { "Yahoo blog" });
			Console.WriteLine(retObj);

			Console.ReadLine();



		}
	}
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post