7月18日考试

15 阅读5分钟

C#考试

基础题目

1: 按照要求写出ArrayList 中的api

(1)

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList al = new ArrayList();

        // 1: 将数组arr变为ArrayList
        int[] num = { 1, 2, 3, 3, 4, 3, 5 };
        foreach (int n in num)
        {
            al.Add(n);
        }

        // 2: num去重处理
        ArrayList distinctAl = new ArrayList();
        for (int i = 0; i < al.Count; i++)
        {
            if (!distinctAl.Contains(al[i]))
            {
                distinctAl.Add(al[i]);
            }
        }
        al = distinctAl;

        // 3: num去重后排序处理
        al.Sort();

        // 4: 查询al中是否存在 "123"
        bool contains123 = al.Contains(123);
        Console.WriteLine("ArrayList contains 123: " + contains123);

        // 5: 将al变为int数组
        int[] intArray = new int[al.Count];
        for (int i = 0; i < al.Count; i++)
        {
            intArray[i] = (int)al[i];
        }
        Console.WriteLine("ArrayList converted to int array: " + string.Join(", ", intArray));
        Console.ReadKey();
    }
}

(2)

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        // 初始化
        string[] arr = { "aaa", "bbb", "bbb", "ccc", "ddd", "ddd" };
        ArrayList al = new ArrayList(arr);

        // 1: al 去重处理,得到 res
        ArrayList res = new ArrayList();
        foreach (string s in al)
        {
            if (!res.Contains(s))
            {
                res.Add(s);
            }
        }

        // 2: 找到al中 ccc第一次出现的位置
        int indexOfCcc = al.IndexOf("ccc");
        Console.WriteLine("Index of 'ccc': " + indexOfCcc);

        // 3: 验证al中是否存在 bbb
        bool containsBbb = al.Contains("bbb");
        Console.WriteLine("ArrayList contains 'bbb': " + containsBbb);

        // 4: 将“eee"添加道al中
        al.Add("eee");

        // 5: 统计 “ddd” 出现的次数
        int countDdd = 0;
        foreach (string s in al)
        {
            if (s == "ddd")
            {
                countDdd++;
            }
        }
        Console.WriteLine("'ddd' count: " + countDdd);

        // 6: 删除al中”bbb"
        while (al.Contains("bbb"))
        {
            al.Remove("bbb");
        }

        // 7: 将 string[] strs = {"aaa","aaa","aaa"} 中每个元素;从al中索引2的位置插入
        string[] strs = { "aaa", "aaa", "aaa" };
        int insertIndex = 2;
        foreach (string s in strs)
        {
            al.Insert(insertIndex, s);
            insertIndex++;
        }

        // 8: 将al变为字符串。用—链接得到 str
        string str = string.Join("-", al.ToArray());
        Console.WriteLine("Joined string: " + str);

        // 9: 统计str中有几个 -
        int dashCount = str.Split('-').Length - 1;
        Console.WriteLine("Number of '-': " + dashCount);

        // 10: 颠倒 al 数组
        al.Reverse();

        // 输出结果验证
        Console.WriteLine("Reversed ArrayList: " + string.Join(", ", al.ToArray()));
        Console.ReadKey();
    }
}

(3)

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string str = "aaa-bbb-ccc-dd-ee-fff-ccc";

        // 1: 将str变为字符串数组 不包含 "-"
        string[] strArray = str.Split('-');
        Console.WriteLine("String array: " + string.Join(", ", strArray));

        // 2: 删除字符串中所有的bbb
        str = str.Replace("bbb", "");
        Console.WriteLine("After removing 'bbb': " + str);

        // 3: 将字符串变为char[]数组
        char[] charArray = str.ToCharArray();
        Console.WriteLine("Char array: " + string.Join(", ", charArray));

        // 4: 将str字符串中所有的ccc变为eee
        str = str.Replace("ccc", "eee");
        Console.WriteLine("After replacing 'ccc' with 'eee': " + str);

        // 5: 将str字符串第一个ccc变为“你好”
        int firstCccIndex = str.IndexOf("ccc");
        if (firstCccIndex != -1)
        {
            str = str.Substring(0, firstCccIndex) + "你好" + str.Substring(firstCccIndex + 3);
        }
        Console.WriteLine("After replacing first 'ccc' with '你好': " + str);

        // 6: 删除str中2位置后5个字符
        if (str.Length > 7) // Ensure there are enough characters to remove
        {
            str = str.Remove(2, 5);
        }
        Console.WriteLine("After removing 5 characters after index 2: " + str);

        // 7: 将str变为StringBuilder类型
        StringBuilder sb = new StringBuilder(str);
        Console.WriteLine("StringBuilder: " + sb.ToString());

        // 8: 将str中前半部分的字母变大写
        int halfLength = str.Length / 2;
        sb = new StringBuilder(str.Substring(0, halfLength).ToUpper() + str.Substring(halfLength));
        Console.WriteLine("First half to uppercase: " + sb.ToString());

        // 9: 将str中所有字母变大写
        sb = new StringBuilder(str.ToUpper());
        Console.WriteLine("All to uppercase: " + sb.ToString());

        // 10: 将str中-链接的字母变为大写
    for (int i = 0; i < sb.Length; i++)
    {
        if (sb[i]=='-')
        {
            sb[i - 1] = char.ToUpper(sb[i-1]);
            sb[i + 1] = char.ToUpper(sb[i+1]);
        }
    }
    Console.WriteLine("After uppercasing all letters linked by '-':"+sb.ToString());
        Console.ReadKey();
    }
}

// 1:创建一个Person类型,字符: 姓名 年龄 身份证号
//   创建三个Person实例,zs  ls  wr
using System;

class Person
{
    // 定义Person的属性
    public string Name { get; set; }
    public int Age { get; set; }
    public string IdNumber { get; set; }

    // 构造函数
    public Person(string name, int age, string idNumber)
    {
        Name = name;
        Age = age;
        IdNumber = idNumber;
    }

    // 重写ToString方法,方便打印Person对象信息
    public override string ToString()
    {
        return $"Name: {Name}, Age: {Age}, ID Number: {IdNumber}";
    }
}

class Program
{
    static void Main()
    {
        // 创建三个Person实例
        Person zs = new Person("张三", 30, "123456789");
        Person ls = new Person("李四", 25, "987654321");
        Person wr = new Person("王五", 28, "555555555");

        // 打印每个Person的详细信息
        Console.WriteLine(zs);
        Console.WriteLine(ls);
        Console.WriteLine(wr);
    }
}

// 根据要求创建类
// 1:创建一个Person类型,字符: 姓名 年龄 身份证号  
//    方法:Say 私有的实例方法
//	       GetName  公共实例方法,作用返回实例的姓名
//		   SetName  作用:修改实例的姓名
// 2: 创建一个Student类: 字符:班级,性别
      继承Person
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 超市系统_控制台_
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建Person实例
            Person zs = new Person("张三", 30, "123456789");
            Console.WriteLine("Person Name: " + zs.GetName());
            zs.SetName("李三");
            Console.WriteLine("Updated Person Name: " + zs.GetName());
            zs.InvokeSay();

            // 创建Student实例
            Student student = new Student("王五", 20, "987654321", "Class 1", "Male");
            Console.WriteLine("Student Name: " + student.GetName());
            Console.WriteLine("Student Class: " + student.Class);
            Console.WriteLine("Student Gender: " + student.Gender);
            Console.ReadKey();
        }
    }
    class Person
    {
        // 定义Person的属性
        public string Name { get; private set; }
        public int Age { get; set; }
        public string IdNumber { get; set; }

        // 构造函数
        public Person(string name, int age, string idNumber)
        {
            Name = name;
            Age = age;
            IdNumber = idNumber;
        }

        // 私有的实例方法
        private void Say()
        {
            Console.WriteLine("Hello, my name is " + Name);
        }

        // 公共实例方法,返回实例的姓名
        public string GetName()
        {
            return Name;
        }

        // 公共实例方法,修改实例的姓名
        public void SetName(string newName)
        {
            Name = newName;
        }

        // 调用Say方法,用于演示
        public void InvokeSay()
        {
            Say();
        }
    }
    class Student : Person
    {
        // 定义Student的属性
        public string Class { get; set; }
        public string Gender { get; set; }

        // 构造函数
        public Student(string name, int age, string idNumber, string className, string gender)
            : base(name, age, idNumber)
        {
            Class = className;
            Gender = gender;
        }
    }

}

5:写出ArrayList中api:作用:参数 结果

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList al = new ArrayList();

        // 增加
        al.Add("aaa");
        al.Add("ccc");

        // 插入
        al.Insert(1, "bbb");

        // 删除
        al.Remove("aaa");
        al.RemoveAt(1);

        // 获取元素第一次出现的位置
        int index = al.IndexOf("bbb");
        Console.WriteLine("Index of 'bbb': " + index);

        // 排序
        al.Add("ddd");
        al.Sort();
        Console.WriteLine("Sorted ArrayList: " + String.Join(", ", al.ToArray()));

        // 颠倒数组
        al.Reverse();
        Console.WriteLine("Reversed ArrayList: " + String.Join(", ", al.ToArray()));

        // 数组变字符串
        string[] arr = (string[])al.ToArray(typeof(string));
        string result = String.Join("-", arr);
        Console.WriteLine("ArrayList as string: " + result);
    }
}

简单题

1. class 的作用是什么?

class 是面向对象编程中的基本构建块,用于定义对象的属性(数据成员)和行为(方法)。它提供了一个模板,通过它可以创建多个对象实例。类封装了数据和操作数据的方法,使代码更易于管理和维护。

2. static 的作用是什么?

static 关键字用于声明静态成员,静态成员属于类而不属于类的实例。静态成员在类级别共享,所有实例共享同一个静态成员。可以用来声明静态字段、方法、属性和构造函数。

3. publicprotectedprivate 的区别是什么?

  • public:公共访问修饰符,表示可以从任何地方访问。
  • protected:受保护的访问修饰符,表示只能在同一个类或派生类中访问。
  • private:私有访问修饰符,表示只能在同一个类中访问。

4. 如何定义类的实例属性?

实例属性是在类中定义的字段,每个实例都有独立的这些字段。可以通过getset访问器来定义属性。

class MyClass
{
    public int MyProperty { get; set; }
}

5. 如何定义类的静态私有属性?

静态私有属性是通过在类中使用staticprivate关键字定义的,只能在类内部访问。

class MyClass
{
    private static int MyStaticProperty { get; set; }
}

6. 如何定义类的静态公共属性?

静态公共属性是通过在类中使用staticpublic关键字定义的,可以从任何地方访问。

class MyClass
{
    public static int MyStaticProperty { get; set; }
}

7. 如何定义虚拟函数?

虚拟函数使用virtual关键字声明,允许在派生类中重写。

class BaseClass
{
    public virtual void MyMethod()
    {
        Console.WriteLine("BaseClass MyMethod");
    }
}

8. override 的作用是什么?

override 关键字用于在派生类中重写基类的虚拟方法或抽象方法。

class DerivedClass : BaseClass
{
    public override void MyMethod()
    {
        Console.WriteLine("DerivedClass MyMethod");
    }
}

9. 类的哪些内容可以被继承?

类的公共和受保护的成员(字段、属性、方法和事件)可以被继承。私有成员不能被继承,但可以通过公共或受保护的方法访问。

10. static class Foo 类能继承吗?

不能。静态类不能被继承,也不能继承其他类。

11. 静态属性可以继承吗?

不能直接继承静态属性,但可以在派生类中通过类名访问基类的静态属性。

12. 类有哪些特点?

  • 封装:将数据和操作数据的方法封装在一起。
  • 继承:可以从基类继承,重用代码。
  • 多态:通过方法重载和重写实现多态。
  • 抽象:可以定义抽象类和方法。

13. 数据类型分类

数据类型分为值类型和引用类型。

14. 值类型有哪些数据类型?

  • 基本数据类型:intfloatdoublecharbool
  • 结构体:struct
  • 枚举:enum

15. 引用类型有哪些数据类型?

  • 类:class
  • 接口:interface
  • 数组:Array
  • 字符串:string
  • 委托:delegate
  • 动态类型:dynamic

16. 函数有哪几个部分组成,作用是什么?

  • 函数名:标识函数的名称。
  • 返回类型:指定函数返回值的数据类型。
  • 参数列表:指定函数的输入参数。
  • 函数体:包含执行代码。

17. 函数的参数作用?refoutparams 区别

  • ref:按引用传递参数,要求在调用前初始化。
  • out:按引用传递参数,不要求在调用前初始化,但要求在函数内部初始化。
  • params:用于传递不定数量的参数。

18. 如何输出函数的运算结果?

通过返回值或使用out参数输出结果。

int Sum(int a, int b)
{
    return a + b;
}

19. foreach 使用的前提条件是什么?

目标集合必须实现IEnumerable接口。

20. 类中变量的访问权限有几种?

三种:publicprotectedprivate

21. 什么是变量的作用域?

变量的作用域指的是变量在代码中可以被访问的范围。局部变量的作用域仅限于它所在的块,实例变量的作用域是它所在的类,静态变量的作用域是它所在的类且在所有实例之间共享。

编程题

1:创建一个类Http,用于描述url地址:

案例如下:
{
	host:"http://",
	ip:"www.baidu",
	port:com
}
using System;

class Http
{
    // 定义Http类的属性
    public string Host { get; set; }
    public string Ip { get; set; }
    public string Port { get; set; }

    // 构造函数
    public Http(string host, string ip, string port)
    {
        Host = host;
        Ip = ip;
        Port = port;
    }

    // 重写ToString方法,方便打印Http对象信息
    public override string ToString()
    {
        return $"{Host}{Ip}.{Port}";
    }
}

class Program
{
    static void Main()
    {
        // 创建Http实例
        Http http = new Http("http://", "www.baidu", "com");

        // 打印Http实例的信息
        Console.WriteLine(http);
    }
}

2:对象排序:

1:创建student类型 字段 姓名 年两 分数
2:创建5个同学;并录入具体信息
3:将5个同学对象放在集合中
4:5个同学按照陈成绩排序
5:表格输出排序后的结果
using System;
using System.Collections;

class Student : IComparable
{
    // 学生类的字段
    public string Name { get; set; }
    public int Age { get; set; }
    public double Score { get; set; }

    // 构造函数
    public Student(string name, int age, double score)
    {
        Name = name;
        Age = age;
        Score = score;
    }

    // 实现 IComparable 接口的 CompareTo 方法,用于排序
    public int CompareTo(object obj)
    {
        if (obj == null) return 1;

        Student otherStudent = obj as Student;
        if (otherStudent != null)
        {
            // 按照分数降序排序
            return otherStudent.Score.CompareTo(this.Score);
        }
        else
        {
            throw new ArgumentException("Object is not a Student");
        }
    }

    // 重写 ToString 方法,方便打印学生对象信息
    public override string ToString()
    {
        return $"{Name}\t{Age}\t{Score}";
    }
}

class Program
{
    static void Main()
    {
        // 创建 ArrayList 并添加学生对象
        ArrayList students = new ArrayList()
        {
            new Student("张三", 20, 85.5),
            new Student("李四", 21, 78.2),
            new Student("王五", 19, 92.0),
            new Student("赵六", 22, 81.8),
            new Student("钱七", 20, 88.6)
        };

        // 按照分数排序
        students.Sort();

        // 表格输出排序后的结果
        Console.WriteLine("姓名\t年龄\t分数");
        foreach (var student in students)
        {
            Console.WriteLine(student);
        }
    }
}

3:生成随机6位的字符串

using System.Linq;
using System;

class Program
{
    static void Main()
    {
        // 初始化一个 Random 对象
        Random random = new Random();

        // 定义包含可能字符的字符串
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        // 生成6位随机字符串
        string randomString = new string(Enumerable.Repeat(chars, 6)
            .Select(s => s[random.Next(s.Length)]).ToArray());

        // 输出生成的随机字符串
        Console.WriteLine("随机生成的6位字符串:");
        Console.WriteLine(randomString);
        Console.ReadKey();
    }
}

4:.把输入的字符串中的内容逆置,并保存到新字符串,并输出新字符串的内容。

using System;

class Program
{
    static void Main()
    {
        // 提示用户输入字符串
        Console.WriteLine("请输入一个字符串:");
        string inputString = Console.ReadLine();

        // 将字符串转换为字符数组
        char[] charArray = inputString.ToCharArray();

        // 使用 Array.Reverse 方法逆置字符数组
        Array.Reverse(charArray);

        // 创建新字符串保存逆置后的结果
        string reversedString = new string(charArray);

        // 输出原始字符串和逆置后的字符串
        Console.WriteLine("\n原始字符串:" + inputString);
        Console.WriteLine("逆置后的字符串:" + reversedString);
        Console.ReadKey();
    }
}

5 在歌星大奖赛中,有7个评委为参赛的选手打分,分数为1~100分。选手最后得分为:去掉一个最高分和一个最低分后其余5个分数的平均值。请编写一个方法实现。

using System;

class Program
{
    static void Main()
    {
        // 假设评委的打分
        int[] scores = { 80, 90, 85, 95, 70, 88, 92 };

        // 调用计算最终得分的方法
        double finalScore = CalculateFinalScore(scores);

        Console.WriteLine($"选手的最终得分为:{finalScore}");
        Console.ReadKey();
    }

    static double CalculateFinalScore(int[] scores)
    {
        // 寻找最高分和最低分的索引
        int minIndex = 0, maxIndex = 0;
        for (int i = 1; i < scores.Length; i++)
        {
            if (scores[i] < scores[minIndex])
                minIndex = i;
            if (scores[i] > scores[maxIndex])
                maxIndex = i;
        }

        // 初始化总和和计数器
        int sum = 0;
        int count = 0;

        // 计算剩余分数的总和
        for (int i = 0; i < scores.Length; i++)
        {
            if (i != minIndex && i != maxIndex)
            {
                sum += scores[i];
                count++;
            }
        }

        // 计算平均值
        double averageScore = (double)sum / count;

        return averageScore;
    }
}

6: 写一个方法,在一个字符串中查找最长单词,单词之间用空格分隔,并将最长单词作为方法返回值返回。

using System;

class Program
{
    static void Main()
    {
        // 示例字符串
        string inputString = "This is a simple example to find the longest word in a string example";

        // 调用查找最长单词的方法
        string[] longestWords = FindLongestWords(inputString);

        Console.WriteLine("最长的单词是:");
        foreach (string word in longestWords)
        {
            if (word != null) // 过滤掉数组中未使用的部分
            {
                Console.WriteLine(word);
            }
        }

        Console.ReadKey();
    }

    static string[] FindLongestWords(string input)
    {
        // 分割字符串成单词数组
        string[] words = input.Split(' ');

        // 初始化一个数组来存储最长单词,初始大小为 words 的长度
        string[] longestWords = new string[words.Length];

        // 初始化最长单词的长度和数组索引
        int maxLength = 0;
        int index = 0;

        // 遍历单词数组找出最长单词
        foreach (string word in words)
        {
            // 更新最大长度并重置数组
            if (word.Length > maxLength)
            {
                maxLength = word.Length;
                Array.Clear(longestWords, 0, longestWords.Length); // 清空数组
                longestWords[0] = word; // 将新最长单词放入数组
                index = 1; // 重置索引
            }
            // 如果当前单词的长度等于最大长度,则添加到数组中
            else if (word.Length == maxLength)
            {
                longestWords[index] = word;
                index++;
            }
        }

        // 返回存储最长单词的数组
        return longestWords;
    }
}

7:写一个方法,对于给定一个日期,返回该日为星期几。例如2002-3-28返回星期四

using System;

class Program
{
    static void Main()
    {
        // 示例日期
        string dateString = Console.ReadLine() ;

        // 调用方法获取星期几
        string dayOfWeek = GetDayOfWeek(dateString);

        Console.WriteLine($"日期 {dateString} 是:{dayOfWeek}");
        Console.ReadKey();
    }

    static string GetDayOfWeek(string date)
    {
        // 将字符串转换为DateTime对象
        DateTime dateTime = DateTime.Parse(date);

        // 获取DayOfWeek枚举值
        DayOfWeek dayOfWeek = dateTime.DayOfWeek;

        // 根据DayOfWeek枚举值返回相应的中文星期几
        switch (dayOfWeek)
        {
            case DayOfWeek.Sunday:
                return "星期日";
            case DayOfWeek.Monday:
                return "星期一";
            case DayOfWeek.Tuesday:
                return "星期二";
            case DayOfWeek.Wednesday:
                return "星期三";
            case DayOfWeek.Thursday:
                return "星期四";
            case DayOfWeek.Friday:
                return "星期五";
            case DayOfWeek.Saturday:
                return "星期六";
            default:
                return "未知";
        }
    }
}

8: 写一个方法,随机产生10个[20,50]的正整数存放到数组中,并输出数组中的所有元素最大值、最小值、平均值及各元素之和。

using System;

class Program
{
    static void Main()
    {
        // 调用方法生成随机数组并计算所需值
        GenerateAndAnalyzeArray();
        Console.ReadKey();
    }

    static void GenerateAndAnalyzeArray()
    {
        // 定义随机数生成器
        Random random = new Random();

        // 定义数组并生成随机数
        int[] numbers = new int[10];
        for (int i = 0; i < numbers.Length; i++)
        {
            numbers[i] = random.Next(20, 51); // 生成[20, 50]范围内的随机数
        }

        // 计算最大值、最小值、平均值及和
        int max = numbers[0];
        int min = numbers[0];
        int sum = 0;

        foreach (int number in numbers)
        {
            if (number > max)
            {
                max = number;
            }
            if (number < min)
            {
                min = number;
            }
            sum += number;
        }

        double average = (double)sum / numbers.Length;

        // 输出结果
        Console.WriteLine("数组中的元素:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine();
        Console.WriteLine($"最大值:{max}");
        Console.WriteLine($"最小值:{min}");
        Console.WriteLine($"平均值:{average}");
        Console.WriteLine($"元素之和:{sum}");
    }
}