我正在练习构建一个虚拟应用程序,我正在尝试传入一个枚举作为参数,并有一个整数输出参数,该参数将用于设置成员变量( BillsOwed
)。我有两个具体问题:为什么是ComputeRetirementBenefitCost
告诉我我的变量 must be assigned to before control leaves the current method
为什么不是 ComputeRetirementBenefitCost
可以访问我在评论中标记的位置吗?欢迎任何和所有谨慎的 future 设计建议:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GivePromotions
{
//Different Employees in the EmpType enum extend this class
public abstract class Employee
{
public int EmployeeId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime DateHired { get; set; }
public RetirementPackage.RetirementPackageType PackageType { get; set; }
public EmpType Employeetype { get; set; }
public int NetSalary { get; set; }
//I'd like to set the output of ComputeRetirementBenefitCost
//in the member below but Intellisense doesn't pick it up
//on two lines for space, commented because it doesn't work
//int billsOwed = Employee.RetirementPackage
//.ComputeRetirementBenefitCost(Employee.EmpType,out benefitCost)
public virtual void DisplayInformation()
{
Console.WriteLine("Employee information: ");
Console.WriteLine("EmployeeId = {0} ", EmployeeId);
Console.WriteLine("Last name = {0} ", LastName);
Console.WriteLine("First name = {0} ", FirstName);
Console.WriteLine("Date hired = {0} ", DateHired);
Console.WriteLine("Salary = {0} ", NetSalary);
}
public enum EmpType
{
Janitor,
President,
Manager
}
//an Employee 'has-a' Retirement package
public class RetirementPackage
{
public enum RetirementPackageType
{
Basic,
Gold,
Silver,
Platinum,
Black
}
//method of choice here
//ERROR: Output parameter 'benefitCost' must be assigned to before control
//leaves the current method
public void ComputeRetirementBenefitCost(Employee.EmpType e, out int benefitCost)
{
switch (e)
{
case Employee.EmpType.President:
benefitCost = 100000;
break;
case Employee.EmpType.Manager:
benefitCost = 5000;
break;
case Employee.EmpType.Janitor:
benefitCost = 1000;
break;
}
}
}
}
}
最佳答案
- 错误:输出参数“benefitCost”必须在控制之前分配给:
您必须向开关添加“默认值:”或在开关外部设置一个值,因为这三种情况可能都不会被命中。
- 为什么 ComputeRetirementBenefitCost 不可访问
解决第一个问题就可以解决这个问题。 使用 crtl+shif+B 构建并读取错误 ListView 中的错误和警告。通常他们会告诉您到底出了什么问题。
关于c# - 并非所有代码路径都会在方法中返回带有输出参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15954518/