简体   繁体   English

C#中最短的空检查

[英]Shortest null check in c#

Is there a shorter way to write this in c# :有没有更短的方法在c# 中写这个:

if(myobject!=null){

}

In JavaScript we can do this:JavaScript 中,我们可以这样做:

if(myobject){

}

Disclaimer: I know this will match 'true' as well in JavaScript.免责声明:我知道这在 JavaScript 中也会匹配 'true'。 This would only be used on variables that should be a specific type of object.这只会用于应该是特定类型对象的变量。

I found some similar questions, but they're asking slightly different things:我发现了一些类似的问题,但他们提出的问题略有不同:

C# Shortest Way to Check for Null and Assign Another Value if Not C# 检查空值的最短方法,如果不是,则分配另一个值

Best and fastest way to check if an object is null 检查对象是否为空的最佳和最快的方法

How to determine if variable is 'undefined' or 'null'? 如何确定变量是“未定义”还是“空”?

You can obtain the same syntax in C# via operator :您可以通过operator在 C# 中获得相同的语法

  public class MyClass {
    ...
    // True if instance is not null, false otherwise
    public static implicit operator Boolean(MyClass value) {
      return !Object.ReferenceEquals(null, value);  
    }   
  }


....

  MyClass myobject = new MyClass();
  ...
  if (myobject) { // <- Same as in JavaScript
    ...
  }

C# language philosophy is quite different than that of JavaScript. C# 语言哲学与 JavaScript 完全不同。 C# usually forces you to be more explicit about somethings in order to prevent some common programming errors (and I'm sure this also helps simplify the compiler design & test). C# 通常会强制您对某些事情更加明确,以防止一些常见的编程错误(我相信这也有助于简化编译器设计和测试)。

If C# had allowed such an implicit conversion to boolean, you are much more likely to run into programming errors like this:如果 C# 允许这种隐式转换为布尔值,那么您很可能会遇到这样的编程错误:

if(myobject = otherObject)
{
   ...
}

where you've made an assignment instead of an equality check .您在其中进行了分配而不是平等检查 Normally C# prevents such mistakes (so although Dmitry's answer is clever, I'd advise against it).通常 C# 会防止此类错误(因此,尽管 Dmitry 的回答很聪明,但我建议不要这样做)。

Sorry for using an answer and not a comment. 很抱歉使用答案而不是评论。 I don't have enough reputation yet to comment. 我还没有足够的声誉发表评论。

I was just wondering if, now that it is several years later, the answer from Dmitry Bychenko is still accurate? 我只是想知道,现在几年之后,Dmitry Bychenko的回答是否仍然准确? My searching did not turn up any articles or questions more recent, but it just seemed like something such as a simple 我的搜索没有发现任何更近期的文章或问题,但它看起来像是一个简单的东西

if (value)  // like JavaScript
    ... do thing

Would exist in C# by now... 现在会存在于C#......

If you want to Throw an ArgumentNullException eg to check method parameters, there is a handy one-liner to do this:如果你想抛出一个ArgumentNullException例如检查方法参数,有一个方便的单行代码来做到这一点:

_ = x ?? throw new ArgumentNullException(nameof(x));

Here, we try to assign the parameter to the discard _ operator.在这里,我们尝试将参数分配给丢弃_运算符。 The ?? ?? -operator performs a nullcheck. -operator 执行空检查。 If the variable is null, the exception is thrown.如果变量为空,则抛出异常。

In Visual Studio you can add a custom snippet to bind this line to the shortcut arg0 .在 Visual Studio 中,您可以添加自定义代码段以将此行绑定到快捷方式arg0 You only need to type arg0 , double press the TAB key, and to type the parameter name.您只需要输入arg0 ,双击 TAB 键,然后输入参数名称。 Implementing a null check then only takes 2 seconds.实现空检查只需要 2 秒。

Here is the snippet.这是片段。 To import it into Visual Studio, please use this guide: https://docs.microsoft.com/de-de/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2019要将其导入 Visual Studio,请使用本指南: https : //docs.microsoft.com/de-de/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2019

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
    <Header>
        <Title>Argument null check for parameters</Title>
        <Shortcut>arg0</Shortcut>
    </Header>
    <Snippet>
        <Code Language="CSharp">
            <![CDATA[_= $param$ ?? throw new ArgumentNullException(nameof($param$));]]>
        </Code>
        <Declarations>
            <Literal>
                <ID>param</ID>
                <ToolTip>Name of the parameter.</ToolTip>
                <Default>x</Default>
            </Literal>
        </Declarations>
    </Snippet>
</CodeSnippet>

You can use object class static method ReferenceEquals method to find out if the refrence is null or not您可以使用对象类静态方法 ReferenceEquals 方法来确定引用是否为空

  MyClass1 obj = new MyClass1();
        if (object.ReferenceEquals(obj,null))
        {
            Console.Write("obj ref is null");
        }

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

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