你这里有关于类和对象以及委托部分的练习题和答案吗
时间: 2024-03-09 14:50:25 浏览: 33
当然,这里有一些关于类和对象以及委托的练习题和答案,希望能够帮到你。
1. 类和对象
(1)请定义一个学生类`Student`,包含以下属性:姓名、年龄、性别、学号,以及以下方法:学习、休息。请使用C#语言实现。
```csharp
class Student {
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public string StudentId { get; set; }
public void Study() {
Console.WriteLine("学生正在学习");
}
public void Rest() {
Console.WriteLine("学生正在休息");
}
}
```
(2)请定义一个矩形类`Rectangle`,包含以下属性:宽度、高度,以及以下方法:计算面积、计算周长。请使用C#语言实现。
```csharp
class Rectangle {
public double Width { get; set; }
public double Height { get; set; }
public double Area() {
return Width * Height;
}
public double Perimeter() {
return 2 * (Width + Height);
}
}
```
2. 委托
(1)请定义一个委托类型`MyDelegate`,接受两个整型参数,返回一个整型结果。请使用C#语言实现。
```csharp
delegate int MyDelegate(int x, int y);
```
(2)请定义一个求和方法`Add`,接受两个整型参数,返回它们的和。请使用C#语言实现。
```csharp
int Add(int x, int y) {
return x + y;
}
```
(3)请定义一个求差方法`Subtract`,接受两个整型参数,返回它们的差。请使用C#语言实现。
```csharp
int Subtract(int x, int y) {
return x - y;
}
```
(4)请定义一个测试方法`Test`,接受一个委托类型参数`myDelegate`,调用该委托类型的实例并输出结果。请使用C#语言实现。
```csharp
void Test(MyDelegate myDelegate) {
int result = myDelegate(1, 2);
Console.WriteLine(result);
}
```
(5)请编写一个测试程序,调用`Test`方法,分别传入`Add`和`Subtract`方法的实例作为参数,并输出它们的结果。请使用C#语言实现。
```csharp
static void Main(string[] args) {
MyDelegate addDelegate = new MyDelegate(Add);
MyDelegate subtractDelegate = new MyDelegate(Subtract);
Test(addDelegate);
Test(subtractDelegate);
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)