如何使用接口作为字段?

时间:2016-08-03 07:19:15

标签: c#

namespace TestOOP
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal sealed class Student
    {
        private string name;
    }

    internal sealed class Course
    {
        private ICollection<Student> students;

        public ICollection<Student> Students
        {
            get { return this.students; }
            set { this.students = Students; }
        }
    }

    class Program
    {
        static void Main()
        {
            var course = new Course();
            course.Students.Add(new Student());
            Console.WriteLine(course.Students.Count());
        }
    }
}

这就是我的代码。在运行它时,我将对象设置为我尝试将学生添加到课程的行中的对象实例。我需要帮助解释如何将接口用作字段。

3 个答案:

答案 0 :(得分:4)

使用集合属性,在构造期间初始化它们是一种很好的做法,并通过readonly getter公开它们:

internal sealed class Course
{
    readonly List<Student> students = new List<Student>();
    public ICollection<Student> Students
    {
        get { return this.students; }
    }
}

这确保Students属性永远不为null,并且没有代码可以用不同的实例替换支持字段。但是,这并不能使类不可变;您仍然可以在Students集合中添加和删除项目。

使用C#6语法,您还可以使用自动实现的只读属性:

internal sealed class Course
{
    public ICollection<Student> Students { get; } = new List<Student>();
}

答案 1 :(得分:1)

你的问题不是界面,而是你没有为你的变量分配任何东西。

UPDATE dupli d
SET description = (
  SELECT CONCAT('duplicate in ',GROUP_CONCAT(`id` ORDER BY id)) 
  FROM (SELECT * FROM dupli) AS d1  
  WHERE `name` = d.`name` AND id <> d.id ) ;

这将解决它:

MariaDB [yourSchema]> UPDATE dupli d
    -> SET description = (
    ->   SELECT CONCAT('duplicate in ',GROUP_CONCAT(`id` ORDER BY id))
    ->   FROM (SELECT * FROM dupli) AS d1
    ->   WHERE `name` = d.`name` AND id <> d.id ) ;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Rows matched: 4  Changed: 0  Warnings: 1

MariaDB [yourSchema]> select * from dupli;
+----+------+------------------+
| id | name | description      |
+----+------+------------------+
|  1 | foo  | duplicate in 3,4 |
|  2 | bar  | NULL             |
|  3 | foo  | duplicate in 1,4 |
|  4 | foo  | duplicate in 1,3 |
+----+------+------------------+
4 rows in set (0.00 sec)

MariaDB [yourSchema]>

答案 2 :(得分:0)

您需要创建属性Students的实际实例,例如使用类课程的构造函数:

{ "Food" : [ { "Day" : 30, "NumberOfDishes" : 1 } ], "Hours" : [ 0, 2 ] }
{ "Food" : [ { "Day" : 30, "NumberOfDishes" : 2 } ], "Hours" : [ 2, 4 ] }
{ "Food" : [ { "Day" : 30, "NumberOfDishes" : 2 } ], "Hours" : [ 4, 6 ] }
{ "Food" : [ { "Day" : 30, "NumberOfDishes" : 2 } ], "Hours" : [ 6, 8 ] }
{ "Food" : [ { "Day" : 30, "NumberOfDishes" : 2 } ], "Hours" : [ 8, 10 ] }

接口必须由真实类实现。