[英]Can i Do object reflection in C#
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". 在我的主机中,我将其命名为String,即“ Cat”或“ 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#?? 我可以在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
). 我添加了一个名称空间以使其成为“更完整的”示例:在.NET中,您可以将代码“ *”放置在任何名称空间之外,但是通常您将使用名称空间。我将其添加到类的名称之前从控制台获得(
"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") 请注意,这段代码是完全没有用的,因为没有基础
interface
/ class
,就无法轻易地使它们成为speak()
(您可以从此开始进行全反射/动态操作,但这很“糟糕”)
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) (请注意, 我不支持您的工作 ,这在很多方面都是不好的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.