接口属性用法

时间:2014-08-07 05:10:46

标签: c# inheritance

运行控制台应用程序时出错,因为显然P的实例不存在。我不明白的是应该在哪里“新”它?它应该在Employee的构造函数中(当我尝试时它没有工作)??

public class Person
{
    private string name;
    public string Name  // read-write instance property
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
}

interface IEmployee
{
    Person P
    {
        get;
        set;
    }

    int Counter
    {
        get;
    }
}

public class Employee : IEmployee
{
    private Person p;
    public static int numberOfEmployees;
    public Person P  // read-write instance property
    {
        get
        {
            return p;
        }
        set
        {
            p = value;
        }
    }

    private int counter;
    public int Counter  // read-only instance property
    {
        get
        {
            return counter;
        }
    }

    public Employee()  // constructor
    {
        counter = ++counter + numberOfEmployees;
    }
}
class Program
{
    static void Main(string[] args)
    {
        System.Console.Write("Enter number of employees: ");
        Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());

        Employee e1 = new Employee();
        System.Console.Write("Enter the name of the new employee: ");
        e1.P.Name = System.Console.ReadLine();

        System.Console.WriteLine("The employee information:");
        System.Console.WriteLine("Employee number: {0}", e1.Counter);
        System.Console.WriteLine("Employee name: {0}", e1.P.Name);

        Console.ReadLine();
    }
}

2 个答案:

答案 0 :(得分:2)

是的,在您的计划中的某个地方,您错过了这一行

e1.P = new Person();

在阅读名称之前,或者在Employee的构造函数中。

答案 1 :(得分:1)

如果您像这样修改代码,它将起作用

class Program
{
    static void Main(string[] args)
    {
        System.Console.Write("Enter number of employees: ");
        Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());

        Employee e1 = new Employee();

        e.P = new Person(); //add this line

        System.Console.Write("Enter the name of the new employee: ");
        e1.P.Name = System.Console.ReadLine();

        System.Console.WriteLine("The employee information:");
        System.Console.WriteLine("Employee number: {0}", e1.Counter);
        System.Console.WriteLine("Employee name: {0}", e1.P.Name);

        Console.ReadLine();
    }
}