.NET 리플렉션을 사용하여 null 허용 참조 유형 확인
.NET 6에서는 이 작업을 처리하기 위해 특별히 NullabilityInfoContext
API를 도입했습니다.
.NET 6 이전 솔루션
NullabilityInfoContext
API 이전에는 속성을 수동으로 검사하여 null 허용 여부를 확인할 수 있었습니다.
public static bool IsNullable(PropertyInfo property) => IsNullableHelper(property.PropertyType, property.DeclaringType, property.CustomAttributes); public static bool IsNullable(FieldInfo field) => IsNullableHelper(field.FieldType, field.DeclaringType, field.CustomAttributes); public static bool IsNullable(ParameterInfo parameter) => IsNullableHelper(parameter.ParameterType, parameter.Member, parameter.CustomAttributes); private static bool IsNullableHelper(Type memberType, MemberInfo? declaringType, IEnumerable<CustomAttributeData> customAttributes) { // 检查属性本身的 [Nullable] 属性。 var nullable = customAttributes.FirstOrDefault(x => x.AttributeType.FullName == "System.Runtime.CompilerServices.NullableAttribute"); if (nullable != null && nullable.ConstructorArguments.Count == 1) { // 检查第一个参数的值(表示可空性上下文的字节)。 var args = (ReadOnlyCollection<CustomAttributeTypedArgument>)nullable.ConstructorArguments[0].Value!; if (args.Count > 0 && args[0].ArgumentType == typeof(byte)) { return (byte)args[0].Value! == 2; // 2 代表“可空”。 } } // 检查封闭类型的 [NullableContext] 属性。 for (var type = declaringType; type != null; type = type.DeclaringType) { var context = type.CustomAttributes.FirstOrDefault(x => x.AttributeType.FullName == "System.Runtime.CompilerServices.NullableContextAttribute"); if (context != null && context.ConstructorArguments.Count == 1 && context.ConstructorArguments[0].ArgumentType == typeof(byte)) { // 检查第一个参数的值(表示可空性上下文的字节)。 return (byte)context.ConstructorArguments[0].Value! == 2; } } // 未找到合适的属性,因此返回 false。 return false; }
이 방법은 [Nullable]
및 [NullableContext]
속성을 검토하고 이들의 다양한 형태와 의미를 고려합니다. 그러나 속성이 어셈블리에 포함되어 다른 어셈블리의 유형을 리플렉션별로 로드해야 하는 경우는 처리하지 않습니다.
기타 참고사항
[Nullable]
속성이 있을 수 있습니다. 여기서 첫 번째 요소는 실제 속성을 나타내고 후속 요소는 일반 매개변수를 나타냅니다. 위 내용은 .NET 리플렉션을 사용하여 Null 허용 참조 유형을 결정하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!