无法将字符串转换为类类型对象 [英] can not convert String to Class Type Object

查看:87
本文介绍了无法将字符串转换为类类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在输入我的代码.

selectReport = this.CreateReportController(_reportName +"Controller");//调用

方法:

公共IActionController CreateReportController(string className)
{



类型typeClass = Type.GetType(className);
字符串路径= Assembly.GetAssembly(typeClass).Location;

汇编asm = Assembly.LoadFile(path);
如果(asm!= null)
{
对象objTest = Activator.CreateInstance(Type.GetType(className));

IActionController reportController =(IActionController)objTest;

返回reportController;
}
其他
{
返回null;
}
}

typeClass和objTest都为NULL.你有什么主意吗.我怎样才能使对象className(string)恰好是Impredation类的名称.

谢谢,
Shafik

Hi All,

I am putting my Code.

selectReport = this.CreateReportController(_reportName + "Controller");//Calling

Method:

public IActionController CreateReportController(string className)
{



Type typeClass = Type.GetType(className);
string path = Assembly.GetAssembly(typeClass).Location;

Assembly asm = Assembly.LoadFile(path);
if (asm != null)
{
Object objTest = Activator.CreateInstance(Type.GetType(className));

IActionController reportController = (IActionController)objTest ;

return reportController;
}
else
{
return null;
}
}

typeClass and objTest is getting NULL. Do you have any Idea. How can I make object className(string) exactly Implentation class name.

Thanks,
Shafik

推荐答案

尝试任何类型的构造函数:
Try either the typed constructor:
yourClass objTest = Activator.CreateInstance<yourclass>();



或正确使用GetType方法:



or properly using the GetType method:

yourClass objTest = Activator.CreateInstance(yourClass.GetType());



或者如果您具有该类的实例作为对象:



or if you have an instance of the class as an object:

yourClass objTest = Activator.CreateInstance(typeof(yourClassInstance));



此页面可能也很有用... http://msdn.microsoft.com/zh-cn/library/system.activator.createinstance.aspx [



This page might be useful as well... http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx[^]


可能是您没有充分限定自己的名字.
例如
Chances are that you haven''t qualified your name sufficiently.
For example
Type type = Type.GetType("MyForm");

将返回null,而

will return null, whereas

Type type = Type.GetType("MyNamespace.MyForm");

将返回有效的类型.


这篇关于无法将字符串转换为类类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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