I have two classes, Dog and Cat
class Dog
{
public void speak() {
System.out.println("Woof!");
}
}
class Cat
{
public void speak() {
System.out.print("Meow!");
}
}
In my main, I take the name as String, either "Cat", or "Dog".
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
String name = sc.next();
Class<?> cls = Class.forName(name);
Object object = cls.newInstance();
}
Can i do this in C#??
Line by line it would be:
public static void Main(string[] args)
{
string name = Console.ReadLine();
// The second true will ignore case
var cls = Type.GetType("Animals." + name, true, true);
var @object = Activator.CreateInstance(cls);
}
with the various animals like:
namespace Animals
{
public class Dog
{
public void speak()
{
Console.WriteLine("Woof!");
}
}
public class Cat
{
public void speak()
{
Console.WriteLine("Meow!");
}
}
}
I've added a namespace to make it a "more complete" example: in .NET you can have your code *outside" any namespace, but normally you'll use a namespace. I'm prepending it to the name of the class obtained from the console ( "Animals." + name
).
Note that this code is quite useless, because without a base interface
/ class
, you can't easily make them speak()
(you can go full reflection/dynamic from this point onward to do it but it is "bad")
Bad way with dynanic:
dynamic @object = Activator.CreateInstance(cls);
@object.speak();
(note that I'm not supporting what you are doing , it is bad in multiple ways)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.