【问题标题】:C# How to use methods from one class in another classC#如何在另一个类中使用一个类的方法
【发布时间】:2019-03-11 20:37:00
【问题描述】:

下面的代码包含两个类 - DateEmployee

  • Date 类检查日期是否为 1900-2100 之间的有效日期。
  • Employee 类显示员工的姓名、工资和雇用日期。

这里显示的Date 类是我为另一个作业创建的。这一次,我应该使用该类和Employee 类中的SetDate 方法来验证main 方法中的日期(由讲师提供用于测试程序)。

我想知道如何使用Employee 类中的SetDate 方法来引用Date 类,从而可以验证日期。我不确定如何让SetDate 方法与其他类交互。此外,我确信有更简单的方法可以创建执行这些功能的程序,但下面程序中的所有类、方法和构造函数都是必需的。

代码比较长,但我真的只关心应该如何使用Employee 类中的SetDate 方法。

namespace MultiClass
{
class Date
{
    private int Month;
    private int Day;
    private int Year;

    //Default Constructor
    // Sets date to 1/1/1900
    public Date()
    {
        Month = 1;
        Day = 1;
        Year = 1900;
    }

    public Date(int M, int D, int Y)
    {
        SetDate(M, D, Y);
    }

    //Sets Month, Day, and Year to M, D, and Y
    //Uses the ValidateDate method to check for valid date 
    //Uses DisplayDate method to 
    public Boolean SetDate(int M, int D, int Y)
    {
        Month = M;
        Day = D;
        Year = Y;

        if (ValidateDate(M, D, Y))
        {
            Console.WriteLine("The following date is valid:");
            DisplayDate();
            return true;
        }
        else
        {
            Console.WriteLine("Invalid date");
            Console.WriteLine("The date will reset to the defualt value:");
            SetDefaultDate();
            return false;
        }

    }

    private void SetDefaultDate()
    {
        Month = 1;
        Day = 1;
        Year = 1900;
        DisplayDate();
    }
    // Determines if date is valid.
    public Boolean ValidateDate(int M, int D, int Y)
    {

        if (ValidateMonth() && ValidateDay() && ValidateYear())
        {
            return true;
        }
        else
        {
            return false;
        }


    }
    // Determines if month is valid.
    public Boolean ValidateMonth()
    {
        if (Month >= 1 && Month <= 12)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    // Determines if year is valid.
    public Boolean ValidateYear()
    {
        if (Year >= 1900 && Year <= 2100)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    // Determines if day is valid
    public Boolean ValidateDay()
    {

        if (Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8 || Month == 10 || Month == 12)
        {
            if (Day >= 1 && Day <= 31)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if (Month == 4 || Month == 6 || Month == 9 || Month == 11)
        {
            if (Day >= 1 && Day <= 30)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if (Month == 2 && IsLeapYear())
        {
            if (Day >= 1 && Day <= 29)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if (Month == 2 && !IsLeapYear())
        {
            if (Day >= 1 && Day <= 28)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    // Determine if year is a leap year
    public Boolean IsLeapYear()
    {
        if ((Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    // Print date to screen in format M/D/Y
    public void DisplayDate()
    {
        Console.WriteLine(ShowDate());
    }

    public String ShowDate()
    {
        StringBuilder myStringBuilder = new StringBuilder();
        myStringBuilder.AppendFormat("{0} / {1} / {2}", Month, Day, Year);
        return (myStringBuilder.ToString());

    }

}


class Employee
{

    private String FirstName;
    private String LastName;
    private double HourlySalary;
    private Date StartDate;

    // Set Employee name and pay with given values
    // Set Employee Starting Date to 1/1/2018
    public Employee(String First, String Last, double Pay)
    {
        FirstName = First;
        LastName = Last;
        HourlySalary = Pay;
    }

    // Set First Name to given value
    public void SetFirstName(String FName)
    {
        FName = FirstName;
    }

    // Return the First Name
    public String GetFirstName()
    {
        return FirstName;
    }

    // Set Last Name to given value
    public void SetLastName(String LName)
    {
        LName = LastName;
    }

    // Return the Last Name
    public String GetLastName()
    {
        return LastName;
    }

    // Set salary to given value. If value is negative, set to 0
    public void SetSalary(double Pay)
    {
        if (Pay < 0)
        {
            HourlySalary = 0;
        }
        else
        {
            HourlySalary = Pay;
        }
    }

    // Return salary
    public double GetSalary()
    {
        return HourlySalary;
    }

    // Display all employee information
    public void DisplayEmployee()
    {
        Console.WriteLine("{0} {1}", FirstName, LastName);
        Console.WriteLine("{0}", HourlySalary);
    }




    // Set the Starting Date to the provided info
    // Checks to see the date is valid
    // If it isn’t valid, print message and set date to 1/1/1900
    public Boolean SetDate(int Month, int Day, int Year)
    {

    }





    static void Main(string[] args)
    {
        Employee Employee1 = new Employee("Anita", "Job", 10000.00);
        Employee Employee2 = new Employee("Mickey", "Mouse", 250000.00);
        if (!Employee1.SetDate(7, 14, 2015))
        {
            Console.WriteLine("Invalid Date Provided for {0}, {1}. Resetting to 01/01/1900",
            Employee1.GetLastName(), Employee1.GetFirstName());
        }
        if (!Employee2.SetDate(10, 32, 2015))
        {
            Console.WriteLine("Invalid Date Provided for {0}, {1}. Resetting to 01/01/1900",
            Employee2.GetLastName(), Employee2.GetFirstName());
        }
        Employee1.DisplayEmployee();
        Employee2.DisplayEmployee();
        Employee1.SetSalary(Employee1.GetSalary() * 1.10);
        Employee2.SetSalary(Employee2.GetSalary() * 1.10);
        Employee1.DisplayEmployee();
        Employee2.DisplayEmployee();
        Employee2.SetFirstName("Fred");
        Employee2.SetLastName("Flintstone");
        Employee2.SetSalary(50000.00);
        if (!Employee2.SetDate(2, 14, 2005))
        {
            Console.WriteLine("Invalid Date Provided for {0}, {1}. Resetting to 01/01/1900",
            Employee2.GetLastName(), Employee2.GetFirstName());
        }
        Employee2.DisplayEmployee();
        Console.ReadLine();
    }


} 

}

【问题讨论】:

  • 您是否考虑过使用 DateTime 对象而不是创建自己的实现?此外,在 C# 中,您应该使用 setter 而不是 SetFirstNameGetFirstName 等方法,请参阅 stackoverflow.com/questions/11159438/…
  • 将您的Date Class 设置为public 并在您的Employee class 中创建instance,然后使用instance 调用SetDate Method
  • @RuiJarimba 我知道 DateTime 对象。但正如我所说,类中的所有方法都是分配所必需的。我得到了方法,并被告知要向它们添加逻辑。
  • @AbinMathew 如何创建instance?我不熟悉它。
  • @AbinMathew 查看我的使用答案。

标签: c# class if-statement methods


【解决方案1】:

首先,您需要从 Date 类中创建 Date 对象,这将为您提供一个 Date 的实例来使用。然后,您可以使用该 Date 实例调用其上的方法以与之交互。

    public Boolean SetDate(int Month, int Day, int Year)
    {
        if(StartDate==null)  // check if we already have a StartDate object
        {
            StartDate = new Date();  //if we don't create a new one
        }
        return StartDate.SetDate(Month, Day, Year);  //set the date and return result.
    }

【讨论】:

    【解决方案2】:

    试试这个:

    public Boolean SetDate(int Month, int Day, int Year)
    {
        Boolean valid = true;
        // here you validate the date, and assign value of validation to "valid" variable
        StartDate = valid ? new Date(Year, Month, Day) : new Date(1900, 1, 1);
        return valid;
    }
    

    【讨论】:

      【解决方案3】:

      Employee.SetDate 方法需要委托给Date 类的一个实例。

      public bool SetDate(int month, int day, int Year)
      {
          var date = new Date(M: month, D: day, Y: year);
          if (date.ValidateDate())
          {
              this.Date = date;
              return true;
          }
          return false;
      }
      

      话虽如此,我知道您说您需要实现某些方法,所呈现的代码结构非常糟糕。 至少您应该修改该方法以直接采用MultiClass.Date,因为如果不这样做,您将完全错过定义这样一个类的许多好处——甚至没有口头上的抽象。

      public bool SetDate(Date date)
      {
          if (date.ValidateDate())
          {
              this.Date = date;
              return true;
          }
          return false;
      }
      

      那你就这样称呼它

      var employee = new Employee();
      employee.SetDate(new Date(3, 9, 1986));
      

      进一步的想法:

      该程序需要数百个其他主要到次要的改进,但我不会在此提及它们。

      根据您的评论,我假设您的老师要求您实现方法的功能,但方法签名是由他提供的。

      鉴于此,你应该问你的老师,虽然不是这些话,也不是我措辞所暗示的轻蔑语气,为什么他在学习 Java 后从不费心学习 C#,为什么他在学习 C++ 后从不费心学习 Java ,以及为什么他在学了 C 之后再也懒得学 C++。

      无论如何,不​​管他的原因是什么,根据我的经验,这通常是懒惰,你不能依赖他教你语言,所以你必须独立完成。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        相关资源
        最近更新 更多