在控制台应用程序中使用Reflection动态创建和调用类 [英] Dynamically creating and calling a class using Reflection in a console application
本文介绍了在控制台应用程序中使用Reflection动态创建和调用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用C#语言的本节中有一些问题。
I have some problems about this section in C# language.
因此,我正在尝试做一些事情,例如揭示此类及其方法的反映。
So I'm trying to do something like revealing reflection of this class and it's methods.
class Car
{
public string Name { get; set; }
public int Shifts{ get; set; }
public Car(string name, int shifts)
{
Name = name;
Shifts = shifts;
}
public string GetCarInfo()
{
return "Car " + Name + " has number of shifts: " + Shifts;
}
}
所以我有这个汽车类,这个方法GetCarInfo (),现在,我正在尝试:
动态创建此类Car的实例,并动态调用方法GetCarInfo(),我想在控制台中显示结果,但是在运行它时无法显示它显示了构建错误。应用程序每次都会中断。
So I have this class Car, and this method GetCarInfo(), now, I'm trying to: Dynamically create instance of this class Car, and dynamically calling a method GetCarInfo(), I would like to show result in console, but I can't when I run it it shows build errors. The application break every time.
推荐答案
以下是示例
namespace ConsoltedeTEstes
{
class Program
{
static void Main(string[] args)
{
//Get the type of the car, be careful with the full name of class
Type t = Type.GetType("ConsoltedeTEstes.Car");
//Create a new object passing the parameters
var dynamicCar = Activator.CreateInstance(t, "User", 2);
//Get the method you want
var method = ((object)dynamicCar).GetType().GetMethod("GetCarInfo");
//Get the value of the method
var returnOfMethod = method.Invoke(dynamicCar, new string[0]);
Console.ReadKey();
}
}
public class Car
{
public string Name { get; set; }
public int Shifts { get; set; }
public Car(string name, int shifts)
{
Name = name;
Shifts = shifts;
}
public string GetCarInfo()
{
return "Car " + Name + " has number of shifts: " + Shifts;
}
}
}
这篇关于在控制台应用程序中使用Reflection动态创建和调用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文