如何使用类名在C#中的参数 [英] How to use class name as parameter in C#

查看:149
本文介绍了如何使用类名在C#中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是自动创建一些对象。



在Java中,类可以通过为参数,例如:



  A级{

}


对象createObjectBy(类clazz所){
// ..做建筑工作,在这里$使用它的时候,只是---> b $ b}

; createObjectBy(的A.class)



它是很多东西的好处。



所以,我该怎么办在C#中类似的事情????


解决方案

 对象createObjectBy(类型clazz所){
// ..做在这里建设工作
对象theObject = Activator.CreateInstance(clazz所);
返回theObject;
}



用法:

  createObjectBy(typeof运算(A)); 



或者你可以简单地使用 Activator.CreateInstance 直接: - )


what i want to do is to automatically create some object.

In Java, class can be pass as parameter, for example

Class A{

}


Object createObjectBy(class clazz){
       // .. do construction work here
}

when using it, just ---> createObjectBy(A.class)

it is benefit for a lot of things.

so, how can i do similar thing in C#????

解决方案

Object createObjectBy(Type clazz){
   // .. do construction work here
    Object theObject = Activator.CreateInstance(clazz);
    return theObject;
}

Usage:

createObjectBy(typeof(A));

Or you could simply use Activator.CreateInstance directly :-)

这篇关于如何使用类名在C#中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆