1)程序设计题1:已知相册类为Album,照片类为Photo,请使用索引器设计容量为5的相册存放照片,需要实现索引器的读/写功能;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace cs1
{
public class Album {
private Photo[] p;//类类型的数组,私有
public int size = 5;
public Album() { //类中构造函数初始化
p=new Photo[size];
}
public Photo this[int index] { //索引器,不是函数,不一定要返回值
get
{
if(index >= 0 || index < p.Length)
{
return p[index];
}
else
{
throw new IndexOutOfRangeException("下标错误!");
}
}
set
{
if(index>=0|| index < p.Length) {
p[index] = value;
}
else
{
throw new ArgumentOutOfRangeException("下标错误!");
}
}
}
}
public class Photo
{
public string Name { get; set; }//为啥要get set?
public Photo(string name)
{
Name = name;
}
}
class Program
{
static void Main(string[] args) {
Album album = new Album();
album[0] = new Photo("Photo 1:me");
album[1] = new Photo("Photo 2:family");
album[2] = new Photo("Photo 3:study");
// 读取并打印相册中的照片信息
for (int i = 0; i < album.size; i++)
{
if (album[i] != null)
{
//这个$在""前加可以使内部的{}换成相应的值,不加的话就把""内部当普通字符串一起输出了
Console.WriteLine($"Photo at index {i}: {album[i].Name} ");
Console.ReadLine();
}
}
}
}
}
1 public string Name { get; set; } 的用法:
在C#中,public string Name { get; set; } 定义了一个自动实现的属性。这里的 get 和 set 访问器允许读取(get)和写入(set)属性的值。
get 访问器用于返回属性的当前值,而 set 访问器用于设置属性的新值。自动实现的属性由编译器在后台自动创建一个私有的字段来存储属性的值,而不需要显式地声明这个字段。
此例中,创建了一个 Photo 类,该类有一个 Name 属性。当我们创建一个 Photo 对象时,我们可以使用 set 访问器给 Name 属性赋值。之后可以使用 get 访问器读取该属性的值并打印它。
不使用 get 和 set 访问器的话就无法读取或设置属性的值。例如如下。
public class Person {
// 只是一个字段,不是属性
public string Name; }
因为Album类中已经说了Photo类被弄成索引器了,所以Photo内部的属性必须也是有索引器性质的get,set。
2这个$在""前加可以使内部的{}换成相应的值,不加的话就把""内部当普通字符串一起输出了
Console.WriteLine($"Photo at index {i}: {album[i].Name} ");
2)程序设计题2:已知person类下包含教师和学生两个子类,请使用接口实现收作业功能;
(我设置的是两个学生A和B来收作业,老师不负责直接收作业)
using System;
namespace cs1
{
interface collecthomework
{
void f();//收作业的方法
}
abstract class People
{
}
class Teacher : People
{
//老师啥都不用做
}
class Astudent : People, collecthomework
{
public void f() { Console.WriteLine("接口收作业,A学生收"); } //类中重写接口中的方法必须用public,不然做不了
}
class Bstudent : People, collecthomework
{
public void f() { Console.WriteLine("接口收作业,B学生收"); } //类中重写接口中的方法必须用public,不然做不了
}
class Program
{
static void docollecthomework(collecthomework work)//执行这个通道需要搞一个做这个接口的通道
{
work.f();
}
static void Main(string[] args)
{
collecthomework a = new Astudent();//让A同学收作业
docollecthomework(a);
Console.ReadLine();
}
}
}