简体   繁体   中英

Marking C# 8 nullable reference types as “this can't be null”

I am trying the new nullable reference types C# 8.0. I have come to one tiny issue:

foreach(FileSystemAccessRule rule in directorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
    // do something with rule
}

This shows a warning since the compiler thinks the rule could be null , which it never will be.

My current fix is this:

foreach(FileSystemAccessRule? rule in directorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
    if (rule == null) continue;
    // do something with rule
}

But I would be much happier with a fix, like [NeverNull]FileSystemAccessRule rule or something like that. Is there a way to achieve this?

if AuthorizationRuleCollection doesn't declare the nullability, or declares them as nullable: the compiler is right to complain. You can use the dammit operator, though, if you're sure:

rule!.DoTheThing();

There is an open issue (at time of writing) to perhaps change this rule slightly in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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