簡體   English   中英

C#如何在另一個類中使用一個類中的方法

[英]C# How to use methods from one class in another class

下面的代碼包含兩個類DateEmployee

  • Date類檢查日期是否為1900-2100之間的有效日期。
  • Employee類顯示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();
    }


} 

}

首先,您需要從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.
    }

嘗試這個:

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;
}

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 ++。

無論如何,無論他的原因是什么,在我的經驗中通常都是懶惰,您不能依靠他來教您這種語言,因此您必須獨立進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM