从另一个类的if语句返回字符串
本文关键字:语句 返回 字符串 if 另一个 | 更新日期: 2024-09-24 20:16:53
我的代码在我的公共静态字符串ValidateCreditScore(int creditscore,string status)中返回一个错误:不能在此作用域中声明名为"status"的本地或参数,因为该名称在封闭的本地作用域中用于定义本地或参数。
基本上,我只想返回那个语句,这样我就可以把它放在占位符中,它说"{0}是{1},applicationName,application.status。我想在声明中说出姓名,并说明信用评分是否可以接受。
我的问题是,我甚至需要我的公共静态字符串ValidateCreditScore(int creditscore,string status)中的字符串状态吗?还是我需要它,因为我要退货。。。
using System;
public class MortgageApplication
{
public static void Main(string[] args)
{
int creditScore = 0;
string applicantName = "";
char userInput = 'n';
string status = "";
Console.WriteLine("** CSCC Mortgage Company **");
Console.Write("'nWould you like to run this program [y, n]? ");
userInput = Convert.ToChar(Console.ReadLine());
while (!(userInput == 'n'))
{
Console.Write("Please enter the applicant's name: ");
applicantName = Console.ReadLine();
Console.Write("Enter credit score: ");
creditScore = Convert.ToInt32(Console.ReadLine());
try
{
Applicant applicant = new Applicant(applicantName, creditScore, status);
Console.WriteLine("{0} is {1}", applicantName,applicant.status);
}
catch (ArgumentException anyException)
{
Console.WriteLine(anyException.Message);
}
Console.Write("Would you like to run this program [y, n]? ");
userInput = Convert.ToChar(Console.ReadLine());
}
Console.WriteLine("Please press the <enter> key to terminate the program.");
Console.ReadLine();
}
}
public class Applicant
{
public Applicant(string name, int creditscore, string status)
{
Name = name;
CreditScore = creditscore;
status = ValidateCreditScore(creditscore, status);
}
public string Name { get; private set; }
public double CreditScore { get; private set; }
public string status { get; private set; }
public static string ValidateCreditScore(int creditscore, string status)
{
try
{
if (creditscore <= 299 && creditscore >= 851)
{
throw new ArgumentException("Value does not fall within the expected range.");
}
if (creditscore <= 649)
{
string status = Convert.ToString("not accepted");
return status;
}
if (creditscore >=650 )
{
string status = Convert.ToString("accepted");
return status;
}
}
catch (ArgumentException anyException)
{
Console.WriteLine(anyException.Message);
}
return "Not Accepted";
}
}
您之所以出现此错误,是因为您将一个名为status
的变量传递到方法中,但随后您也试图声明一个同名的变量。你甚至不需要在方法中声明变量,你可以这样重写你的代码:
if (creditscore <= 649)
{
return "not accepted";
}
if (creditscore >=650 )
{
return "accepted";
}
方法ValidateCreditScore中不需要状态参数。只需返回字符串,而不必使用以下变量:…
return Convert.ToString("accepted");
或
return Convert.ToString("not accepted");
因此,在方法中删除该参数并修复生成错误。
您收到错误是因为传递到ValidateCreditScore
的变量之一被命名为"status"
public static string ValidateCreditScore(int creditscore, string status)
但是稍后您尝试创建另一个同名变量:
if (creditscore <= 649)
{
string status = Convert.ToString("not accepted");
return status;
}
将其中一个变量重命名为其他变量,它应该可以工作。
此外,不需要Convert.ToString()
,并且在返回字符串之前不需要将其存储在变量中
if(creditscore <= 649)
{
return "not accepted";
}
最后,看起来传递到ValidateCreditScore
的状态甚至没有在函数中使用,所以你可以去掉它