Reflection
Reflection is mainly used for Read MetaData of an object.Structurally, metadata is a normalized relational database. This means that metadata is organized as a set of cross-referencing rectangular tables
The below example we have used TYPE,FIELDINFO, METHODINFO methods for getting the metadata information.The "Type" type is important when using reflection.We can search fields by using the GetField and GetFields methods,We can search methods by using the GetMethods and GetMethods methods.
Example
static void Main()
{
//Create an Type of Program
Type type = typeof(Program);
//get Field info
FieldInfo field = type.GetField("_number");
object temp = field.GetValue(null);
Console.WriteLine(temp);
//
//Get all Methods
MethodInfo[] methods = type1.GetMethods();
foreach (MethodInfo info in methods)
{
Console.WriteLine(info.Name);
// Call getData method.
if (info.Name == "getData")
{
info.Invoke(customer, null); // fire method
}
}
}
string _name;
int _age;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
get
{
return _age;
}
set
{
_age = value;
}
}
public void getData()
{
Console.WriteLine("Get Data Called");
Console.ReadLine();
}
}
}
Note: get & set properties as consider as a methods in reflection. It will display along with list of Methods.
Reflection is mainly used for Read MetaData of an object.Structurally, metadata is a normalized relational database. This means that metadata is organized as a set of cross-referencing rectangular tables
The below example we have used TYPE,FIELDINFO, METHODINFO methods for getting the metadata information.The "Type" type is important when using reflection.We can search fields by using the GetField and GetFields methods,We can search methods by using the GetMethods and GetMethods methods.
Example
class Program
{
public static int _number = 7;static void Main()
{
//Create an Type of Program
Type type = typeof(Program);
//get Field info
FieldInfo field = type.GetField("_number");
object temp = field.GetValue(null);
Console.WriteLine(temp);
//
CUSTOMER customer = new CUSTOMER();
Type type1 = typeof(CUSTOMER);//Get all Methods
MethodInfo[] methods = type1.GetMethods();
foreach (MethodInfo info in methods)
{
Console.WriteLine(info.Name);
// Call getData method.
if (info.Name == "getData")
{
info.Invoke(customer, null); // fire method
}
}
}
public class CUSTOMER
{string _name;
int _age;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Age
{get
{
return _age;
}
set
{
_age = value;
}
}
public void getData()
{
Console.WriteLine("Get Data Called");
Console.ReadLine();
}
}
}
Note: get & set properties as consider as a methods in reflection. It will display along with list of Methods.
No comments:
Post a Comment