【问题标题】:Dynamically creating and calling a class using Reflection in a console application在控制台应用程序中使用反射动态创建和调用类
【发布时间】:2019-07-07 12:10:36
【问题描述】:

我对这部分的 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(),我想在控制台中显示结果,但是当我运行它时无法显示构建错误。应用程序每次都会中断。

编辑

Errors

【问题讨论】:

  • 你能更好地解释一下“动态创建实例”、“动态调用方法”等是什么意思吗?你想做什么?
  • 你的意思是这样的? stackoverflow.com/questions/40915110/…
  • @n0idea 我现在将发布构建错误和代码,以便您更好地理解。请稍等。
  • @BugCatcherJoe 我是新手,但我认为不一样。
  • @xVenum.dll 正如我在代码注释中所说,要小心命名空间,您需要类的完整命名空间来获取类型,正如我在示例 Type.GetType 中所示("ConsoltedeTEstes.Car");

标签: c# dynamic reflection


【解决方案1】:

这是一个例子

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;
    }

}


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多