Dynamically creating and calling a class using Ref

2019-08-21 04:28发布

问题:

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

}

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.

Edit

Errors

回答1:

Here's a example

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 dinamycCar = Activator.CreateInstance(t, "User", 2);

        //Get the method you want
        var method = ((object)dinamycCar).GetType().GetMethod("GetCarInfo");

        //Get the value of the method
        var returnOfMethod = method.Invoke(dinamycCar, 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;
    }

}


}