I want to instantiate an object of a class using Activator.CreateInstance
. So, I have an ASP.Net MVC project under which i have a folder called Modal and under that i have one class TestClass.cs
.
我想使用Activator.CreateInstance实例化一个类的对象。所以,我有一个ASP.Net MVC项目,我有一个名为Modal的文件夹,在其下我有一个类TestClass.cs。
Now i have another Class Library project. So have i written the instantiation login inside one of the class of my Class Library project and copy the .dll
file inside my main ASP.Net MVC project.
现在我有另一个类库项目。所以我在我的类库项目的一个类中编写了实例化登录,并将.dll文件复制到我的主ASP.Net MVC项目中。
Now from my main project i requested to my recently add Class Library project to create an Object of the class by passing FullyQualified name of my class.
现在从我的主项目我请求我最近添加的类库项目通过传递我的类的FullyQualified名称来创建类的对象。
EX:
ASP.Net MVC Project
ASP.Net MVC项目
------------------------------
`
namespace MyProject.Modal
{
public class TestClass
{
public TestClass()
{
}
}
}
`
Class Library Project Code
`
namespace SpringNet.FactoryContext
{
public class CreateInstance
{
public Object GetClass(string FullyQualifiedName)
{
Object NewClassType = null;
Type ClassName = Type.GetType(FullyQualifiedName);
NewClassType = Activator.CreateInstance(ClassName);
return NewClassType;
}
}
}
`
Now i build my Class library project and added reference to my ASP.Net MVC Project and tries to create the object.
CreateInstance instance = new CreateInstance();
var NewObject = instance.GetClass("MyProject.Modal.TestClass");
After calling this i am getting exception
在打电话给我后,我得到了例外
Type ClassName = Type.GetType(FullyQualifiedName);
Type ClassName = Type.GetType(FullyQualifiedName);
at this line only i am not able to get the type of class what i am requesting for.
在这一行只有我无法得到我要求的类型。
Please help. Thanks in advance.
请帮忙。提前致谢。
1 个解决方案
#1
0
You can try this one:
你可以尝试这个:
namespace SpringNet.FactoryContext
{
public class CreateInstance
{
public Object GetClass(string assemblyName,string className)
{
return Activator.CreateInstance(assemblyName, className);
}
}
}
And then
CreateInstance instance = new CreateInstance();
var NewObject = instance.GetClass("MyProject", "MyProject.Modal.TestClass");
Updated: Why Type.GetType return null
更新:为什么Type.GetType返回null
Type.GetType("namespace.a.b.ClassName") returns null
Type.GetType(“namespace.a.b.ClassName”)返回null
#1
0
You can try this one:
你可以尝试这个:
namespace SpringNet.FactoryContext
{
public class CreateInstance
{
public Object GetClass(string assemblyName,string className)
{
return Activator.CreateInstance(assemblyName, className);
}
}
}
And then
CreateInstance instance = new CreateInstance();
var NewObject = instance.GetClass("MyProject", "MyProject.Modal.TestClass");
Updated: Why Type.GetType return null
更新:为什么Type.GetType返回null
Type.GetType("namespace.a.b.ClassName") returns null
Type.GetType(“namespace.a.b.ClassName”)返回null