//Add this method to previous code im Programme class
private static Object createNewObject(string className)
{
Type objectType = Type.GetType(className);
Object newObject = Activator.CreateInstance(objectType);
return newObject;
}
// returns an object of spesified type as a given string parameter
// and you can calll this method as
Object newObj = createNewObject("Reflection.Employee");
// thats all..
5 Ağustos 2010 Perşembe
REflection, Advanced Programming
Here is how we reach class info at runtime.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Reflection
{
class Program
{
static void Main(string[] args)
{
Employee myEmployee = new Employee();
Type objectType = myEmployee.GetType();
ConstructorInfo[] constInfo = objectType.GetConstructors();
MethodInfo[] methodInfo = objectType.GetMethods();
FieldInfo[] fieldInfo = objectType.GetFields();
Console.WriteLine("Constructors");
foreach (ConstructorInfo info in constInfo)
{
Console.WriteLine(info);
}
Console.WriteLine("Methods");
foreach (MethodInfo info in methodInfo)
{
Console.WriteLine(info);
}
Console.WriteLine("Fields");
foreach (FieldInfo info in fieldInfo)
{
Console.WriteLine(info);
}
}
}
}
// We have an employee class
class Employee : EmployeeBase
{
private int id;
private string name;
public Employee()
{
}
public Employee(int id)
{
this.id = id;
}
public string GetName()
{
return this.name;
}
}
// and we have an EmployeeBase class
class EmployeeBase
{
string baseField;
public void BaseMethod() { }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Reflection
{
class Program
{
static void Main(string[] args)
{
Employee myEmployee = new Employee();
Type objectType = myEmployee.GetType();
ConstructorInfo[] constInfo = objectType.GetConstructors();
MethodInfo[] methodInfo = objectType.GetMethods();
FieldInfo[] fieldInfo = objectType.GetFields();
Console.WriteLine("Constructors");
foreach (ConstructorInfo info in constInfo)
{
Console.WriteLine(info);
}
Console.WriteLine("Methods");
foreach (MethodInfo info in methodInfo)
{
Console.WriteLine(info);
}
Console.WriteLine("Fields");
foreach (FieldInfo info in fieldInfo)
{
Console.WriteLine(info);
}
}
}
}
// We have an employee class
class Employee : EmployeeBase
{
private int id;
private string name;
public Employee()
{
}
public Employee(int id)
{
this.id = id;
}
public string GetName()
{
return this.name;
}
}
// and we have an EmployeeBase class
class EmployeeBase
{
string baseField;
public void BaseMethod() { }
}
Kaydol:
Kayıtlar (Atom)