开发者

Type.GetType Failing but property.PropertyType Works Fine

开发者 https://www.devze.com 2022-12-08 07:18 出处:网络
I am iterating through the object and initializing all the properties of that object. First the type of the object i.e class was placed in my same project and it worked fine. Now, I moved the class in

I am iterating through the object and initializing all the properties of that object. First the type of the object i.e 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.

Here is my previous code:

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

The above always returned 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. 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.

But hey, if you already have the type as a Type from the PropertyType property, there's no point in calling Type.GetType anyway :)

0

精彩评论

暂无评论...
验证码 换一张
取 消