The .Net Framework provides a reflection capability that allows you to obtain information about assemblies, modules and types as well as being able to dynamically create instances of types. In this article, I explain how to get type information and create instances dynamically.
Let's start with a simple example with an existing .Net class. Consider at run-time, you want to get a list of class properties. To achieve this, we must first import the
System.Reflection namespace. Once imported the
Type class can be used to get details about a class using the
GetType() method as seen in the example below.
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
PropertyInfo[] propInfoList = Type.GetType("System.DateTime").GetProperties();
foreach (PropertyInfo propInfo in propInfoList)
{
Console.WriteLine(propInfo.Name);
}
Console.ReadKey();
}
}
In the above code the GetProperties() method will return an array of PropertyInfo objects for the
System.DateTime Type. The PropertyInfo class has a
Name property, which will return the public property name of the reflecting class. To get a list of non public properties, you can use a bitmask comprised of
System.Reflection.BindingFlags as shown in the example below.
PropertyInfo[] propInfoList = Type.GetType("System.DateTime").GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
We can also use the GetMethod() method to get a list of public methods.
MethodInfo[] methodInfoList = Type.GetType("System.DateTime").GetMethods();
foreach (MethodInfo methodInfo in methodInfoList)
{
Console.WriteLine(methodInfo.Name);
}
BindingFlags can also be used to get a list of non public methods. Reflection can also be used to get a list of all class attributes using the GetCustomAttributes() method.
object[] attrs = Type.GetType("System.String").GetCustomAttributes(true);
foreach (Attribute attr in attrs)
{
Console.WriteLine(attr.ToString());
}
You can also filter the attributes if you need to find a particular attribute.
object[] attrs = Type.GetType("System.String").GetCustomAttributes(Type.GetType("System.SerializableAttribute"), true);
No comments:
Post a Comment