简体   繁体   English

区分 C# 中显式可为空的字符串类型

[英]Distinguish an explicitly nullable string type in C#

There are a lot of examples of string properties with "nullable" vs "non-nullable" declarations:有很多带有“可空”和“不可空”声明的字符串属性示例:

public MyClass {
    public string NotNullable {get;set;}
    public string? Nullable {get;set;}
}

This is even shown in the Microsoft C# official documentation on nullables as the primary example of nullable types.这甚至显示在Microsoft C# 官方文档中,关于可空值作为可空类型的主要示例。

This is made confusing by the fact that strings in C# can be null by default. C# 中的字符串默认情况下可以是 null ,这让人感到困惑。

string myString = null; //100% valid, compile-able code

I have a script where I'm checking the types of properties in a class, to see if they are nullable.我有一个脚本,我正在检查 class 中的属性类型,以查看它们是否可以为空。 It's a long story why, but these nullable flags are put in a list and exported.这是一个很长的故事,但是这些可以为空的标志被放在一个列表中并导出。

bool nullable = false;
if (classProperty.PropertyType.IsGenericType 
   && classProperty.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
    nullable = true;
}

This works for int?这适用于int? s, class references, DateTime? s,class 参考, DateTime? objects, basically anything other than string?对象,基本上除了string? , it can determine if it's an explicitly-declared nullable property or not. ,它可以确定它是否是显式声明的可空属性。

Is there any way to determine if a property is string versus string?有什么方法可以确定属性是string还是string? , and if not, why have (and laud in the documentation) a nullable string type for C#? ,如果没有,为什么(并在文档中称赞)C# 的可空字符串类型?


Also tried也试过

An alternate method, comparing the PropertyType to a type derived directly:另一种方法,将PropertyType与直接派生的类型进行比较:

modelProperty.PropertyType == typeof(int) //works
modelProperty.PropertyType == typeof(int?) //works
modelProperty.PropertyType == typeof(double) //works
modelProperty.PropertyType == typeof(double?) //works
modelProperty.PropertyType == typeof(string) //works
modelProperty.PropertyType == typeof(string?) //NOPE!

C# vomits an error about not being able to use the typeof operator on a nullable type when passed string? C# 在传递string? despite having literally just done so without issue for int?尽管实际上只是这样做了,但int? and double?double? . . Also, modelProperty == typeof(string) is true whether the property was declared with either string or string?此外, modelProperty == typeof(string)是 true,无论属性是用string还是string? . .

@Jesse got me pointed in the right direction. @Jesse 让我指出了正确的方向。 If anyone comes looking later, this is how I ended up checking and it seems to be working across the board:如果有人稍后再看,这就是我最终检查的方式,它似乎正在全面工作:

if(modelProperty.PropertyType == typeof(string)
&& modelProperty.GetMethod?.CustomAttributes.Where(x => x.AttributeType.Name == "NullableContextAttribute").Count() == 0){
    nullable = true;
}

Still glad to entertain any more succinct answers!仍然很高兴接受任何更简洁的答案!

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

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