在另一个类中实例化对象而不是main方法

时间:2016-09-15 19:38:48

标签: c# oop

下面我创建了一个名为'Staff'的简单类。当我尝试在main方法中实例化一个新的staff对象时,一切都很完美。为什么它在main方法中有效,而不是在我的语法“Frog”中?

class staff
{
    //Fields
    private string nameOfStaff;
    private const int hourlyRate = 30;
    private int hWorked;

    //Properties
    public int HoursWorked
    {
        get
        {
            return hWorked;
        }
        set
        {
            if (value > 0)
                hWorked = value;
            else
                hWorked = 0;
        }
    }


    //Methods
    public void PrintMessage()
    {
        Console.WriteLine("Calculating Pay...");
    }

    public int CalculatePay()
    {
        PrintMessage();

        int staffPay;
        staffPay = hWorked * hourlyRate;

        if (hWorked > 0)
            return staffPay;
        else
            return 0;
    }

    public int CalculatePay(int bonus, int allowances)
    {
        PrintMessage();
        if (hWorked > 0)
            return hWorked * hourlyRate + bonus + allowances;
        else
            return 0;
    }

    public override string ToString()
    {
        return "Name of Staff = " + nameOfStaff + ", hourlyRate = " + hourlyRate + ", hWorked = " + hWorked;
    }

    //Constructors
    public staff(string name)
    {
        nameOfStaff = name;
        Console.WriteLine("\n" + nameOfStaff);
        Console.WriteLine("-------------------------");
    }

    public staff(string firstName, string lastName)
    {
        nameOfStaff = firstName + " " + lastName;
        Console.WriteLine("\n" + nameOfStaff);
        Console.WriteLine("-------------------------");
    }

}

class Program
{
    static void Main(string[] args)
    {
        // Instanciating an Object
        int pay;
        staff staff1 = new staff("Peter");
        staff1.HoursWorked = 160;
        pay = staff1.CalculatePay(1000, 400);
        Console.WriteLine("Pay = {0}", pay);
 }

 class frog 

 {
  // Why can't I instantiate a staff member here?
 }

3 个答案:

答案 0 :(得分:3)

您可能希望将代码从main移到frog 构造函数中,您可以在其中访问字段,方法和属性:

 class frog 
 {
   public staff Staff {get; set;} 

   public frog() {
     Staff = new staff("Peter");

     // Now do everything you like with the Staff  
     Staff.HoursWorked = 160;  
   }  
 }

答案 1 :(得分:0)

所以也许我没有正确地提出这个问题(因为我不知道答案)但是我能够弄清楚......

 class frog
{
    static void newStaff()
    {
        staff staff4 = new staff;
        staff4.HoursWorked
    }
}

我不确定static void newStaff()的作用,但它允许代码编译。显然这里新尝试学习..

答案 2 :(得分:0)

当您尝试从类中实例化一个新对象时,它需要在方法内部或类的构造函数中完成。

只有通过方法调用才能创建对象,因此在方法或构造函数之外实例化它是行不通的。