如何从存储在字符串中的名称中获取类对象
亲爱的所有人,
我面临一些关于使用存储在字符串中的名称来获取课程类型的愚蠢问题。
这是我的案例:
我有一个人力资源项目包括以下内容:
1- HR.Core 类库项目,其中包含我的课程(员工,部门,......)
2- HR.Domain .....
3- HR.Repository .....
.....
4- HRApp 这是包含我的视图,模型和cotrollers的Web应用程序,此项目包含其他项目的参考。
------------------------
现在在 HRApp 我希望员工类使用其存储在字符串中的名称。
我尝试过Type.GetType(HR.Core.Employee)
但它总是返回null。
---------------- --------
通知 如果我放HR.Core项目中的相同代码在某种类型的mehtod中称为 test ,它可以成功运行。
任何人都可以告诉我怎么了?
Dear All,
I am facing some silly problem about getting class type using its name stored in a string.
Here is my Case:
I have a HR project Consists of the Following:
1- HR.Core Class Library Project which contains my classes (Employee, Department, ....)
2- HR.Domain .....
3- HR.Repository .....
.....
4- HRApp which is the web application that contains my views, models and cotrollers and this project contains a reference of the other projects.
------------------------
Now in HRApp i want to get Employee Class using its Name which is stored in a string.
I tried Type.GetType("HR.Core.Employee")
But it always returns null.
------------------------
Notice that if i put the same code inside the HR.Core project in some kind mehtod called test, it works successfully.
Can any one tell me whats wrong?
当按名称使用GetType时,你需要提供一个更全面的合格名称。
GetType(MyNamespace.MyClass,MyAssembly)
所以
GetType(HR.Core.Employee,HR.Core)
我假设Employee类是一个名为HR.Core的程序集,但可能不是。示例Core项目的项目属性,它将说明程序集的调用内容。
但是一般情况下,您可能采取了错误的方法。写丢失这样的代码来绕过你忘记做事很少是一个合适的解决方案。
When using GetType by name you need to give a fuller qualified name.
GetType("MyNamespace.MyClass, MyAssembly")
So
GetType("HR.Core.Employee, HR.Core")
above I am assuming the Employee class is an assembly called HR.Core, but it might not be. Example the project properties of the Core project and it will say what the assembly is called.
However in general it seems you're probably taking the wrong approach. Writing lose code like this to get around you forgetting to do things is rarely a proper solution.