visual c# 2005中的方法输入
本文关键字:方法 输入 2005 visual | 更新日期: 2023-09-27 17:52:13
我在Visual Studio c# 2005中创建控制台应用程序时遇到了一个问题
我创建了以下程序,其中在程序
中调用了一个方法(对两个预定义的值求和)下面是它的代码
class program
{
static void Main()
{
program a;
a = new program();
Console.WriteLine(a.am1(1,2));
Console.ReadLine();
}
int sum;
public int am1(int num1, int num2)
{
sum = num1 + num2;
return sum;
}
}
现在这是我面临的主要问题,在这个程序中,两个整数(num1和num2)是预定义的,我希望这两个数字是从用户那里取的,意味着用户输入两个数字,然后同样的程序像上面一样继续。应该怎么做呢?
p。记住,所有的事情都应该在方法中完成
我希望我得到了你的要求…如果没有,请详细说明!
public sealed class Program
{
private readonly int _number1;
private readonly int _number2;
public Program(int number1, int number2)
{
this._number1 = number1;
this._number2 = number2;
}
public int Sum()
{
return this._number1 + this._number2;
}
public static void Main(string[] args)
{
// this one here is really brutal, but you can adapt it
int number1 = int.Parse(args[0]);
int number2 = int.Parse(args[1]);
Program program = new Program(number1, number2);
int sum = program.Sum();
Console.WriteLine(sum);
Console.ReadLine();
}
}
对不起,这不是我的主要编码风格…pfuh……真丑!
编辑:- 不要盲目信任
int.Parse()
。参数来自用户,您最好仔细检查它们! - 你最好三次检查它们,因为你正在做一个求和…值得庆幸的是,c#可以用
unchecked
编译-如果在vb中编译,这段代码可能会因为OverflowException
而失败-记住int
的范围 - 为什么你想在一个额外的类中做一个简单的添加?
- 你应该详细说明你的风格(关于你的评论):将ui代码与业务层代码分开!
- 你不需要为每个任务创建一个实例变量——你也可以用作用域变量这样做…!
- …
使用控制台应用程序命令行参数。如果你觉得合适的话。下面是来自MSDN的一个例子。
public class Functions
{
public static long Factorial(int n)
{
// Test for invalid input
if ((n < 0) || (n > 20))
{
return -1;
}
// Calculate the factorial iteratively rather than recursively:
long tempResult = 1;
for (int i = 1; i <= n; i++)
{
tempResult *= i;
}
return tempResult;
}
}
class MainClass
{
static int Main(string[] args)
{
// Test if input arguments were supplied:
if (args.Length == 0)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Try to convert the input arguments to numbers. This will throw
// an exception if the argument is not a number.
// num = int.Parse(args[0]);
int num;
bool test = int.TryParse(args[0], out num);
if (test == false)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Calculate factorial.
long result = Functions.Factorial(num);
// Print result.
if (result == -1)
System.Console.WriteLine("Input must be >= 0 and <= 20.");
else
System.Console.WriteLine("The Factorial of {0} is {1}.", num, result);
return 0;
}
}
// If 3 is entered on command line, the
// output reads: The factorial of 3 is 6.