如何从方法返回空值

本文关键字:返回 空值 方法 | 更新日期: 2023-09-27 18:32:40

我是Java程序员,我是C#的新手,我真的不明白为什么需要Nullable类型。谁能解释我? 例如,我有代码:

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

属性值类型是"字符串"而不是"字符串?",但"GetAttribute"可以返回 null。 所以,事实上,我应该为每个变量检查它的值是否为 null,那么为什么通常需要可为空的类型"*?"呢? 它怎么能有用?

第二个问题:如何使用返回类型"string"编写我自己的方法并从中返回 null 值?

如何从方法返回空值

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

如果需要可为空的struct("值类型"),请使用 Nullable<T>(或相同的T?)。 class es("引用类型")始终可为空,就像在 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;
}

你可以将返回类型作为string并返回null,因为字符串是引用类型,它也可以保存null

public string SomeMethod()
{
    return null;
}

属性值类型是"字符串"而不是"字符串?"

带有?的数据类型是仅适用于值类型的Nullable<T>数据类型,因为字符串是不能string?的引用类型。 ?只是句法糖。

在 C# 和 Visual Basic 中,通过使用 ?值类型后的表示法。

您可能还会看到:值类型和引用类型

回答最后一个问题:

路漫漫其修远兮:

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

短途:

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

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

按如下方式调用此方法:

string returnedString;
returnedString = MethodReturnsString();

returnedString将充满来自MethodReturnsString(); "this is a string"