简体   繁体   English

Type.GetType失败但property.PropertyType工作正常

[英]Type.GetType Failing but property.PropertyType Works Fine

I am iterating through the object and initializing all the properties of that object. 我正在迭代对象并初始化该对象的所有属性。 First the type of the object ie class was placed in my same project and it worked fine. 首先,对象的类型,即类放在我的同一个项目中,它工作正常。 Now, I moved the class into a different project but still making the same object by using AssemblyName.Namespace.Class but it stopped working. 现在,我将类移动到另一个项目中,但仍使用AssemblyName.Namespace.Class创建相同的对象,但它已停止工作。

Here is my previous code: 这是我以前的代码:

var o = Activator.CreateInstance(Type.GetType(property.PropertyType.Name)); 

The above always returned null. 以上总是返回null。 So, I tried the following: 所以,我尝试了以下内容:

var o = Activator.CreateInstance(property.PropertyType); 

and it worked and created the correct object. 它工作并创建了正确的对象。 I am curious why this happened! 我很好奇为什么会这样!

Type.GetType(string) requires the full name of the type, including assembly information, unless the type is in the same assembly as the caller or mscorlib. Type.GetType(string)需要类型的名,包括程序集信息,除非该类型与调用者或mscorlib位于同一程序集中。 Additionally, you need to make sure you've got the namespace as well. 此外,您还需要确保您已获得命名空间。 So Type.FullName should work within the same assembly or mscorlib, and Type.AssemblyQualifiedName should always work. 因此Type.FullName应该在同一个程序集或mscorlib中工作,并且Type.AssemblyQualifiedName应该始终有效。

But hey, if you already have the type as a Type from the PropertyType property, there's no point in calling Type.GetType anyway :) 但是,嘿,如果你已经从PropertyType属性中将类型作为Type ,那么无论如何调用Type.GetType都没Type.GetType :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM