当前位置: 首页 > 编程语言 > C#

如何通过反射区分值类型、可为空值类型、枚举、可为空枚举和引用类型?分享

时间:2023-04-10 10:54:05 C#

如何通过反射区分值类型、可为空值类型、枚举、可为空枚举和引用类型?如何通过反射区分值类型、可为空值类型、枚举、可为空枚举和引用类型?enumMyEnum{一、二、三}classMyClass{publicintIntegerProp{get;放;公共诠释?NullableIntegerProp{得到;放;}publicMyEnumEnumProp{get;放;publicMyClassReferenceProp{get;放;}}classProgram{staticvoidMain(string[]args){类型classType=typeof(MyClass);PropertyInfopropInfoOne=classType.GetProperty("IntegerProp");PropertyInfopropInfoTwo=classType.GetProperty("NullableIntegerProp");PropertyInfopropInfoThree=classType.GetProperty("EnumProp");PropertyInfopropInfoFour=classType.GetProperty("NullableEnumProp");PropertyInfopropInfoFive=classType.GetProperty("ReferenceProp");propInfoOne.???....................................}}propInfo中可以获取哪些信息?以下是检查枚举、可空、原始和值类型的方法;控制台.WriteLine(propInfoOne.PropertyType.IsPrimitive);//真Console.WriteLine(propInfoOne.PropertyType.IsValueType);//false,值类型是结构Console.WriteLine(propInfoThree.PropertyType.IsEnum);//truevarnullableType=typeof(Nullable).MakeGenericType(propInfoThree.PropertyType);Console.WriteLine(nullableType.IsAssignableFrom(propInfoThree.PropertyType));//true请注意,值类型和原语是不同的东西原语只是映射到类型的简写(例如bool>System.Boolean)。值类型按值传递;它们是结构(ure)而不是类。publicvoidTest(TypedesiredType,objectvalue){if(desiredType.IsGenericType){if(desiredType.GetGenericTypeDefinition()==typeof(Nullable)){if(value==null){}}}}PropertyType.Name似乎beNonNullable和Nullable类型提供不同的输出。也许这对你有点帮助。实际上它给出Nullable`1Int32作为Nullable和Nonnullable的输出。以上就是C#学习教程:如何通过反射区分值类型、可为空值类型、枚举、可为空枚举、引用类型?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: