gpt4 book ai didi

c# - 具有异常处理的方法参数

转载 作者:太空宇宙 更新时间:2023-11-03 21:55:29 25 4
gpt4 key购买 nike

我显然是 C# 的新手,下面的程序来自 Charles Petzold 的一本书,我并不完全理解。 GetDouble 方法中的参数是一个名为 prompt 的字符串。没有任何地方宣布这一点,我认为这就是让我感到困惑的原因。我看到 Main 方法正在调用 GetDouble 并将三个字符串打印到控制台,但这整件事对我来说看起来很奇怪。这是典型的编程设计,还是这不是行业标准,而是为了展示如何做事?无论哪种方式,这本书都没有给出答案。我初出茅庐的编程 self 不会将字符串传递给 Main 方法。有人可以帮我理顺一下吗?

using System;

class InputDoubles
{
static void Main()
{
double dbase = GetDouble("Enter the base: ");
double exp = GetDouble("enter the exponent: ");
Console.WriteLine("{0} to the power of {1} is {2}", dbase, exp, Math.Pow(dbase, exp));
}

static double GetDouble(string prompt)
{
double value = Double.NaN;
do
{
Console.Write(prompt);
try
{
value = Double.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine();
Console.WriteLine("you enter an invalid number!");
Console.WriteLine("please try again");
Console.WriteLine();

}
}

while (Double.IsNaN(value));
return value;

}
}

最佳答案

Nowhere is this declared and I think that's what's messing me up.

等等,它就在那里声明 - 在方法的 header 中:

static double GetDouble(string prompt)
// ^^^^^^^^^^^^^ This is the declaration of prompt

prompt 与您看到的其他变量不同,它不是普通变量:它是方法的形式参数

与使用赋值运算符 = 初始化和显式赋值的常规变量不同,形式参数通过调用方法隐式赋值.当您调用该方法时,您将一个带有实际参数 的表达式传递给它,该表达式充当该表达式对形式参数的赋值。假设 prompt 变量在第一次调用之前被赋值 "Enter the base: ",然后被赋值 "enter the exponent: "在第二次调用之前了解调用 GetDouble 时发生了什么。

关于c# - 具有异常处理的方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12479057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com