C# 9: Simplified Parameter Null Validation

栏目: IT技术 · 发布时间: 5年前

内容简介:When we last reported onThe rules are pretty straight forward.Regarding the constructor rule, Microsoft did consider allowing the parameter check to occur before invoking the base class constructor. This has always been allowed by .NET and is arguably pref

When we last reported on Simplified Parameter Null Validation , this feature was being challenged by several competing proposals ranging from attributes and compilers flags to full scale AOP with IL weaving. All of that has been discarded in favor of a narrowly tailored feature proposal which reduces the amount of code needed to validate non-null parameters to a single character.

The bang operator, !, can be positioned after any identifier in a parameter list and this will cause the C# compiler to emit standard null checking code for that parameter. For example:

void M(string name!) {
    ...
}

Will be translated into:

void M(string name!) {
    if (name is null) {
        throw new ArgumentNullException(nameof(name));

    }
    ...
}

The rules are pretty straight forward.

==
string? x!

Regarding the constructor rule, Microsoft did consider allowing the parameter check to occur before invoking the base class constructor. This has always been allowed by .NET and is arguably preferable. However, the C# syntax doesn’t expose this capability, and they didn’t want to generate code that couldn’t be created without using this feature.

In the test plan , we see these scenarios for generics

void M<T>(T value!) { } is OK
void M<T>(T value!) where T : struct { } is an error
void M<T>(T value!) where T : unmanaged { } is an error
void M<T>(T value!) where T : notnull { } is OK
void M<T>(T value!) where T : class { } is OK
void M<T>(T value!) where T : SomeStruct { } is an error
void M<T>(T value!) where T : SomeClass { } is OK

One flaw in the design is that it offers no support for validating properties, as the value parameter is only implied. Orthoxerox suggested a work-around where the bang operator is applied to the set keyword in this scenario.

public Foo Foo {get; set!;}

public Bar Bar {
    get { return bar; }
    set! { bar = value; DoSomethingElse(); }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

最愚蠢的一代

最愚蠢的一代

马克·鲍尔莱因 / 杨蕾 / 天津社会科学院出版社 / 2011-7 / 39.80元

《最愚蠢的一代》 美国大学教授的鲍尔莱恩认为,数码时代正在使美国的年轻一代成为知识最贫乏的一代人。 美国的青少年和年轻人正在被数码时代各种娱乐消遣性的工具所淹没。这些工具包括手机、社交网络和信息传送等等。他们通过这些工具传达的却是幼稚浮浅的东西,而且这些东西正在妨碍他们同历史、公民义务、国际事务和美术等成年人的现实世界进行重要的接触。 我们想当然地以为,这些善于吸收新技术的美国年......一起来看看 《最愚蠢的一代》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具