[英]Dynamically creating and calling a class using Reflection in a console application
我在 C# 语言中对本节有一些问题。
所以我试图做一些事情,比如揭示这个类的反射及其方法。
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;
}
}
所以我有这个类 Car 和这个方法 GetCarInfo(),现在,我正在尝试:动态创建这个类 Car 的实例,并动态调用一个方法 GetCarInfo(),我想在控制台中显示结果,但我当我运行它时不能显示构建错误。 应用程序每次都中断。
这是一个例子
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.