“退货”和“退货新品”的区别
本文关键字:退货新品 区别 新品 退货 | 更新日期: 2023-09-27 17:55:42
当我阅读 C# 中的扩展方法时,我看到了下面的编码:
public static class ExtensionMethods
{
public static string UpperCaseFirstLetter(this string value)
{
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
}
return value;
}
}
class Program : B
{
static void Main(string[] args)
{
string value = "dot net";
value = value.UpperCaseFirstLetter();
Console.WriteLine(value);
Console.ReadLine();
}
}
我评论了这行,"返回新"礼物并运行程序。现在编译器读取代码"返回值"。如果我运行程序而不注释该行,则编译器不会读取"返回值"行。在 C# 中返回和返回新内容有什么区别?
没有return new
这样的东西。实际发生的是:
string foo = new string(array);
return foo;
您正在返回字符串的实例。
没有return new
,它只是一个return
语句,就像任何其他语句一样。 它返回的是new string(array)
.
如果注释该行,则该方法不会结束,而是退出if
块,继续执行下一个return
语句。
return 关键字将跳过执行并返回函数作为返回类型的值。在您的示例中,它是static string
,因此它会返回字符串。
从操作:
I commented the line, "return new" presents and run the program. Now the compiler reads the code "return value". If I run the program without commenting that line, then the compiler not reads the "return value" line. What is the difference between return and return new in C#?
当您注释"返回新"行时,编译器执行整个功能块,"返回值"得到执行,当"返回新"出现时,编译器读取它并从那里返回流。
我认为
return
让你感到困惑。 采用以下逻辑上相等的代码:
public static string UpperCaseFirstLetter(this string value)
{
string result;
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
result = new string(array);
}
else
{
result = value;
}
return result;
}
new string(array)
调用这个构造函数,该构造函数采用 char 数组并为您提供它的字符串表示形式。 方法签名声明将返回string
。 如果尝试return array
,将发生编译器错误。