Detection of native objects with reflection

I work with reflection based object translator.

it basically goes through the properties of the object and assigns values ​​to properties with the same name / type on the translated object.

ObjectA.Name = "Joe"

translates to:

ObjectB.Name = "Joe"

I need to put in a special case, since the property is a custom class, for example:

ObjectA.Address

i was hoping i could detect such properties with the IsClass PropertyType flag

propInfo.PropertyType.IsClass 

but this flag also returns true for string properties.

Is there any other way to verify that a property is of a non-native type?

+4
source share
2 answers

I assume that you want to determine if the target type is not a primate. You can use TypeCode for this, for example:

 public bool IsNotCoreType(Type type) { return (type != typeof(object) && Type.GetTypeCode(type) == TypeCode.Object); } 

Any non-primitive should return TypeCode.Object as a result of Type.GetTypeCode , so we can check to see if it will get this and that the type itself is not System.Object .

Perhaps this will help?

UPDATE I renamed the method to IsNotCoreType to cover both primitives and non-primitives like String , DateTime , etc. (see comments below).

+5
source
Line

is an exception, the only primitive type in .NET that is a reference type. You should consider this exception in your code to check if IsClass true and the type is not the same as System.String .

+1
source

Source: https://habr.com/ru/post/1332152/


All Articles