C# 返回可为空的字符串类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/928398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning nullable string types
提问by sarsnake
So I have something like this
所以我有这样的事情
public string? SessionValue(string key)
{
if (HttpContext.Current.Session[key].ToString() == null || HttpContext.Current.Session[key].ToString() == "")
return null;
return HttpContext.Current.Session[key].ToString();
}
which doesn't compile.
哪个不编译。
How do I return a nullable string type?
如何返回可为空的字符串类型?
采纳答案by Andy White
String is already a nullable type. Nullable can only be used on ValueTypes. String is a reference type.
String 已经是可空类型。Nullable 只能用于 ValueType。字符串是一种引用类型。
Just get rid of the "?" and you should be good to go!
只是摆脱“?” 你应该很高兴去!
回答by Brandon
You can assign null to a string since its a reference type, you don't need to be able to make it nullable.
您可以将 null 分配给字符串,因为它是一个引用类型,您不需要能够将其设为可空。
回答by Jeff Meatball Yang
String is already a nullable type. You don't need the '?'.
String 已经是可空类型。你不需要'?'。
Error 18 The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'
错误 18 类型“字符串”必须是不可为空的值类型,才能将其用作泛型类型或方法“System.Nullable”中的参数“T”
回答by Steef
string
is already nullable on its own.
string
本身已经可以为空。
回答by Lucas
As everyone else has said, string
doesn't need ?
(which is a shortcut for Nullable<string>
) because all reference types (class
es) are already nullable. It only applies to value type (struct
s).
正如其他人所说,string
不需要?
(这是 的快捷方式Nullable<string>
),因为所有引用类型 ( class
es) 都可以为空。它仅适用于值类型 ( struct
s)。
Apart from that, you should not call ToString()
on the session value before you check if it is null
(or you can get a NullReferenceException
). Also, you shouldn't have to check the result of ToString()
for null
because it should never return null
(if correctly implemented). And are you sure you want to return null
if the session value is an empty string
(""
)?
除此之外,您不应该ToString()
在检查会话值之前调用它null
(或者您可以获得NullReferenceException
)。此外,您不应该检查ToString()
for的结果,null
因为它永远不会返回null
(如果正确实现)。null
如果会话值为空string
( ""
),您确定要返回吗?
This is equivalent to what you meant to write:
这相当于您要编写的内容:
public string SessionValue(string key)
{
if (HttpContext.Current.Session[key] == null)
return null;
string result = HttpContext.Current.Session[key].ToString();
return (result == "") ? null : result;
}
Although I would write it like this (return empty string
if that's what the session value contains):
虽然我会这样写(string
如果会话值包含,则返回空):
public string SessionValue(string key)
{
object value = HttpContext.Current.Session[key];
return (value == null) ? null : value.ToString();
}