For example, I want to create a program that records the book title, author, genre, etc., each book is a separate class object, how can I make it so that I can automatically declare new class objects during the program's operation (I need this for educational purposes)
CodePudding user response:
You can use the Activator.CreateInstance
method to create a new instance of a given type. This example demonstrates the usage.
class MyType
{
public override string ToString()
{
return "My type.";
}
}
MyType obj = Activator.CreateInstance<MyType>();
Console.WriteLine(obj);
If you have a type that has constructor parameters, these can be given in the following way:
class MyTypeWithConstructor
{
string _message;
public MyTypeWithConstructor(string message)
{
_message = message;
}
public override string ToString()
{
return _message;
}
}
object[] parameters = new object[1] { "Hello world!" };
MyTypeWithConstructor obj2 = (MyTypeWithConstructor)Activator.CreateInstance(
typeof(MyTypeWithConstructor), args: parameters);
Console.WriteLine(obj2);