For demonstration purpose I've created a class that contains only private methods,fields and properties
/// <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";
}
To access private fields I used the System.Reflection.FieldInfo class .For private properties I used System.Reflection.PropertyInfo .Note if you want to work with private members you should use System.Reflection.BindingFlags enum as shown in the example below .So for non-static class members the flags should looks like BindingFlags.NonPublic | BindingFlags.Instance .For static don't forget to add BindingFlags.Static .
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();
}
The console output fallows