【问题标题】:How return null from method如何从方法返回null
【发布时间】:2013-09-24 22:22:21
【问题描述】:

我是 Java 程序员,我是 C# 新手,我真的不明白为什么需要 Nullable 类型。任何人都可以解释我吗? 例如我有代码:

 XmlReader xr=...
 string propertyValue=xr.GetAttribute("SomeProperty");
 if(propertyValue!=null) {
 //some code here
}

propertyValue 类型是 'string' 而不是 'string?'但“GetAttribute”可以返回 null。 所以,事实上,我应该为每个变量检查​​它的值是否为空,那么为什么可以为空类型'*?一般是需要的。 它有什么用处?

还有第二个问题: 如何编写我自己的返回类型为 'string' 的方法并从中返回 null 值?

【问题讨论】:

标签: c# nullable


【解决方案1】:

Nullable<T> 类型用于structs。这些有点类似于 Java 的原语(例如,它们不能为空),但更强大和灵活(例如,用户可以创建自己的 struct 类型,您可以在它们上调用 ToString() 之类的方法)。

如果您想要一个可为空的struct(“值类型”),请使用Nullable<T>(或相同的T?)。 classes(“引用类型”)总是可以为空的,就像在 Java 中一样。

例如

//non-nullable int
int MyMethod1()
{
    return 0;
}

//nullable int
int? MyMethod2()
{
    return null;
}

//nullable string (there's no such thing as a non-nullable string)
string MyMethod3()
{
    return null;
}

【讨论】:

    【解决方案2】:

    您可以将返回类型设为string 并返回null,因为字符串是引用类型,它也可以包含null

    public string SomeMethod()
    {
        return null;
    }
    

    propertyValue 类型是 'string' 而不是 'string?'

    带有? 的数据类型是Nullable<T> 数据类型,它只适用于值类型,因为字符串是一个引用类型,你不能拥有string?? 只是语法糖。

    在 C# 和 Visual Basic 中,您可以使用 ?值类型后的符号。

    您可能还会看到:Value Types and Reference Types

    【讨论】:

      【解决方案3】:

      回答最后一个问题:

      漫长的路:

      private string MethodReturnsString()
      {
         string str1 = "this is a string";
         return str1;
      }
      

      捷径:

      private string MethodReturnsString()
      {
         return "this is a string";
      }
      

      str1 填充:"this is a string",将返回给调用它的方法。

      调用这个方法如下:

      string returnedString;
      returnedString = MethodReturnsString();
      

      returnedString 将从MethodReturnsString(); 填充为"this is a string"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-23
        • 2014-10-30
        • 1970-01-01
        • 2013-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多