本次考试以最高分数为最终成绩
考试时间:2024-09-11 16:19至2024-09-20 16:21
按要求编写一个复杂的事件程序:
A.在名空间中添加类MultiStepActionCoordinatorComplexEvent,并按注释添加语句:
//声明名为OnMultiStepActionCoordinatorHandler的直接公开的委托,无返回值,参数为:object类型的sender和MultiStepActionCoordinatorEventArgs类型的e
public class //定义继承于EventArgs的类MultiStepActionCoordinatorEventArgs
{
//类中有两个字段:一个是Int32类型,另一个是DayOfWeek类型
//还有一个双参数的构造函数,方便对字段赋值
}
public class MultiStepActionCoordinatorComplexEvent
{
// 添加类型为OnMultiStepActionCoordinatorHandler的事件公共字段MHandler
// 编写触发事件方法OnMultiStepActionCoordinatorEvent,单MultiStepActionCoordinatorEventArgs类型参数e,负责触发委托事件方法
}
B.在名空间中添加下列类:
public static class StringTransformer
{
public static string TransformTo32Chars(this string input, string key = "your-secret-key")
{
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(input));
string hashInHex = BitConverter.ToString(hashBytes).Replace("-", "");
return hashInHex.Substring(0, 32);
}
}
}
public class EventAnalyzer
{
public static string AnalyzeEvents(MultiStepActionCoordinatorComplexEvent obj)
{
StringBuilder result = new StringBuilder();
var events = obj.GetType().GetEvents(BindingFlags.Public | BindingFlags.Instance);
foreach (var ev in events)
{
result.Append($"Event Name: {ev.Name}\n");
var eventType = ev.EventHandlerType;
result.Append($"Event Delegate Type: {eventType.Name}\n");
result.Append($"Event Subscription Illustration:\n");
result.Append(string.Join("\n", InspectEventHandlers(obj)));
}
return result.ToString().TransformTo32Chars();
}
public static List < string > InspectEventHandlers(MultiStepActionCoordinatorComplexEvent obj)
{
List < string > result = new List < string > ();
FieldInfo eventField = obj.GetType().GetField("MHandler", BindingFlags.Instance | BindingFlags.NonPublic);
if (eventField != null)
{
Delegate currentDelegate = eventField.GetValue(obj) as Delegate;
if (currentDelegate != null)
{
MethodInfo[] methods = currentDelegate.GetInvocationList().Select(d = > d.Method).ToArray();
foreach (MethodInfo method in methods)
{
result.Add(MethodSignatureToString(method));
}
}
else
result.Append("No event handling methods registered.\n");
}
else
result.Append("Unable to retrieve the event field.\n");
return result;
}
private static string MethodSignatureToString(MethodInfo method)
{
string parameters = String.Join(", ", method.GetParameters().Select(p = > p.ParameterType.Name + " " + p.Name));
return $"{method.ReturnType.Name} {method.Name}({parameters})";
}
}
C.在Program类内定义如下表的5个用于委托订阅的方法,每个方法用两个参数:一个是object类型的sender,另一个是MultiStepActionCoordinatorEventArgs类型的e,方法执行输出下表中的对应文字、sender.GetType().Name、e中的两个字段,中间用等号分隔:
方法名 |
输出文字 |
UndergroundFungalFeeder |
Subtle scraping sounds (digging for fungi) |
ArcticMarineMammal |
Sonar-like clicks and whistles (echolocation) |
UnderwaterInvertebrate |
Bright flashing lights (for defense or communication) |
UnderwaterBioluminescentCnidarian |
Bright flashes of light (to attract prey or confuse predators) |
VolcanicVentCreature |
Gentle hissing (due to chemical reactions) |
D.在Program类中Main方法添加如下代码:
//模仿下列注释写好Main方法的执行语句
//var fe = new ConveyRealTimeUpdateComplexEvent();
// 如同下法订阅5个事件过程
//fe.CHandler += new OnConveyRealTimeUpdateHandler(ArcticTundraMigratorySongbird);
//ConveyRealTimeUpdateEventArgs args = new ConveyRealTimeUpdateEventArgs(45, Saturday);
//fe.OnConveyRealTimeUpdateEvent(args);
Console.WriteLine(EventAnalyzer.AnalyzeEvents(fe));
Console.ReadLine();
运行程序,返回结果为: 1
Subtle scraping sounds (digging for fungi)=MultiStepActionCoordinatorComplexEvent=45=Saturday
Sonar-like clicks and whistles (echolocation)=MultiStepActionCoordinatorComplexEvent=45=Saturday
Bright flashing lights (for defense or communication)=MultiStepActionCoordinatorComplexEvent=45=Saturday
Bright flashes of light (to attract prey or confuse predators)=MultiStepActionCoordinatorComplexEvent=45=Saturday
Gentle hissing (due to chemical reactions)=MultiStepActionCoordinatorComplexEvent=45=Saturday
C1D60E31CAAD267038B872BBAEB492B3
Subtle scraping sounds (digging for fungi)=MultiStepActionCoordinatorComplexEvent=45=Saturday
Sonar-like clicks and whistles (echolocation)=MultiStepActionCoordinatorComplexEvent=45=Saturday
Bright flashing lights (for defense or communication)=MultiStepActionCoordinatorComplexEvent=45=Saturday
Bright flashes of light (to attract prey or confuse predators)=MultiStepActionCoordinatorComplexEvent=45=Saturday
Gentle hissing (due to chemical reactions)=MultiStepActionCoordinatorComplexEvent=45=Saturday
920B2894953210454450306C21C12EEF
具体解析
Event Name: MHandler
Event Delegate Type: OnMultiStepActionCoordinatorHandler
Event Subscription Illustration:
Void UndergroundFungalFeeder(Object sender, MultiStepActionCoordinatorEventArgs e)
Void ArcticMarineMammal(Object sender, MultiStepActionCoordinatorEventArgs e)
Void UnderwaterInvertebrate(Object sender, MultiStepActionCoordinatorEventArgs e)
Void UnderwaterBioluminescentCnidarian(Object sender, MultiStepActionCoordinatorEventArgs e)
Void VolcanicVentCreature(Object sender, MultiStepActionCoordinatorEventArgs e)
根据以下信息创建一个clsSportsMatch类和一个strucSportsMatch结构,它们包含4个字段,分别为:
A.int类型的公共字段MatchID、decimal类型的公共字段Attendance、float类型的公共字段HomeTeamScore、double类型的公共字段AwayTeamScore;
B.包含一个构造函数用于给个字段赋值;
模仿下列例子,写出自己的clsSportsMatch类和strucSportsMatch结构:
// 新的类实例:clsEmployee
public class clsEmployee
{
// 公共字段
public string EmployeeID;
public string FirstName;
public string LastName;
public DateTime HireDate;
public decimal AnnualSalary;
// 构造函数
public clsEmployee(string employeeid, string firstName, string lastname, DateTime hiredate, decimal annualsalary)
{
this.EmployeeID = employeeid;
this.FirstName = firstname;
this.LastName = lastname;
this.HireDate = hiredate;
this.AnnualSalary = annualsalary;
}
public override string ToString()
{
return $"{EmployeeID},{FirstName},{LastName},{HireDate},{AnnualSalary}";
}
}
// 新的结构体实例:strucEmployee
public struct strucEmployee
{
// 公共字段
public string EmployeeID;
public string FirstName;
public string LastName;
public DateTime HireDate;
public decimal AnnualSalary;
// 构造函数
public strucEmployee(string employeeid, string firstName, string lastname, DateTime hiredate, decimal annualsalary)
{
this.EmployeeID = employeeid;
this.FirstName = firstname;
this.LastName = lastname;
this.HireDate = hiredate;
this.AnnualSalary = annualsalary;
}
public override string ToString()
{
return $"{EmployeeID},{FirstName},{LastName},{HireDate},{AnnualSalary}";
}
}
clsSportsMatch类的代码: 1 (答案不需要注释语句)
strucSportsMatch结构的代码: 2 (答案不需要注释语句)
在Main方法中写入以下语句,并将运行结果填入 3
var p4 = new strucSportsMatch(3, 46, 96, 86);
var p1 = new clsSportsMatch(3, 46, 96, 86);
var p3 = p4;
var p2 = p1;
Console.WriteLine(p3);
Console.WriteLine(p2);
p3.MatchID = 24;
p2.MatchID = 24;
Console.WriteLine(p1);
Console.WriteLine(p2);
Console.WriteLine(p3);
Console.WriteLine(p4);
class clsSportsMatch
{
public int MatchID;
public decimal Attendance;
public float HomeTeamScore;
public double AwayTeamScore;
public clsSportsMatch(int matchID, decimal attendance, float homeTeamScore, double awayTeamScore)
{
this.MatchID = matchID;
this.Attendance = attendance;
this.HomeTeamScore = homeTeamScore;
this.AwayTeamScore = awayTeamScore;
}
public override string ToString()
{
return $"{MatchID},{Attendance},{HomeTeamScore},{AwayTeamScore}";
}
}
struct strucSportsMatch
{
public int MatchID;
public decimal Attendance;
public float HomeTeamScore;
public double AwayTeamScore;
public strucSportsMatch(int matchID, decimal attendance, float homeTeamScore, double awayTeamScore)
{
this.MatchID = matchID;
this.Attendance = attendance;
this.HomeTeamScore = homeTeamScore;
this.AwayTeamScore = awayTeamScore;
}
public override string ToString()
{
return $"{MatchID},{Attendance},{HomeTeamScore},{AwayTeamScore}";
}
}
3,46,96,86
3,46,96,86
24,46,96,86
24,46,96,86
24,46,96,86
3,46,96,86
public class clsSportsMatch
{
public int MatchID;
public decimal Attendance;
public float HomeTeamScore;
public double AwayTeamScore;
public clsSportsMatch(int matchid,decimal attendance,float hometeamscore,double awayteamscore)
{
this.MatchID = matchid;
this.Attendance = attendance;
this.HomeTeamScore = hometeamscore;
this.AwayTeamScore = awayteamscore;
}
public override string ToString()
{
return $"{MatchID},{Attendance},{HomeTeamScore},{AwayTeamScore}";
}
}
public struct strucSportsMatch
{
public int MatchID;
public decimal Attendance;
public float HomeTeamScore;
public double AwayTeamScore;
public strucSportsMatch(int matchid,decimal attendance,float hometeamscore,double awayteamscore)
{
this.MatchID = matchid;
this.Attendance = attendance;
this.HomeTeamScore = hometeamscore;
this.AwayTeamScore = awayteamscore;
}
public override string ToString()
{
return $"{MatchID},{Attendance},{HomeTeamScore},{AwayTeamScore}";
}
}
3,46,96,86
3,46,96,86
24,46,96,86
24,46,96,86
24,46,96,86
3,46,96,86
具体解析
请按以下要求编写接口程序,并使用表达式体实现MainClass的多重继承:
A.编写接口IGenerateDailyStatisticsSummary,接口包含1个属性:属性1为DateTime类型的只写属性date;
B.编写接口ICompressDirectoryContents,接口包含2个属性:属性1为string类型的只读属性sourceDirPath、属性2为string类型的可读可写属性compressedArchivePath;
新增一个MainClass类,继承以上所有的接口,并实现所有接口中的方法为公共方法,属性的表达式体设置方法如下:
interface kkk
{
string KSDL { set; get; } //标准答案为set在前get在后
}
class MyObject:kkk
{
private string _ksdl;
public string KSDL
{
set = > _ksdl = value; //标准答案为set在前get在后
get = > _ksdl; //别颠倒
}
}
编写实现代码填入 1
public interface IGenerateDailyStatisticsSummary
{
DateTime date { set; }
}
public interface ICompressDirectoryContents
{
string sourceDirPath { get; }
string compressedArchivePath { set; get; }
}
public class MainClass : IGenerateDailyStatisticsSummary, ICompressDirectoryContents
{
private DateTime _date;
private string _sourceDirPath;
private string _compressedArchivePath;
public DateTime date
{
set => _date = value;
}
public string sourceDirPath
{
get => _sourceDirPath;
}
public string compressedArchivePath
{
set => _compressedArchivePath = value;
get => _compressedArchivePath;
}
}
interface IGenerateDailyStatisticsSummary
{
DateTime date { set; }
}
interface ICompressDirectoryContents
{
string sourceDirPath { get; }
string compressedArchivePath { set; get; }
}
class MainClass : IGenerateDailyStatisticsSummary, ICompressDirectoryContents
{
private DateTime _date;
private string _sourcedirpath;
private string _compressedarchivepath;
public DateTime date
{
set => _date = value;
}
public string sourceDirPath
{
get => _sourcedirpath;
}
public string compressedArchivePath
{
set => _compressedarchivepath = value;
get => _compressedarchivepath;
}
}
具体解析
按要求编写一个简单的委托程序:
A.在名空间中添加类DisplayOnScreenMessageWithMethods,并按注释添加语句:
public class DisplayOnScreenMessageWithMethods
{
// 声明名为DisplayOnScreenMessage,返回值为字符串类型,参数也为字符串类型的委托
// 编写方法DoOperation
}
B.在类DisplayOnScreenMessageWithMethods内定义如下表的5个用于委托的方法:
方法名 |
返回文字 |
SubterraneanHeatResistantCrustacean |
Silent (no audible sound, but may cause ripples in underground water sources) |
MarineIlluminatingJellyfish |
Soft glowing pulses (bioluminescent display) |
UnderwaterSpongeFeedingFish |
Mild clicking sounds (during feeding) |
ArcticSurfaceForagingArthropod |
Soft tapping sounds (as they move across the snow surface) |
UnderwaterElectricGenerator |
Electric crackling sounds (when producing electric shocks) |
C.在名空间中添加下列类:
public static class StringTransformer
{
public static string TransformTo32Chars(this string input, string key = "your-secret-key")
{
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(input));
string hashInHex = BitConverter.ToString(hashBytes).Replace("-", "");
return hashInHex.Substring(0, 32);
}
}
}
public class MethodAnalyzer
{
public static (bool Exists, string MethodSignature) AnalyzeMethod(string methodName, Type targetType)
{
var method = targetType.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
if (method == null) return (false, null);
string accessModifier = method.IsPublic ? "public" : "private";
string returnType = method.ReturnType.Name;
var parameterInfos = method.GetParameters();
var parametersWithDelegateDetails = parameterInfos.Select(pi = >
pi.ParameterType.IsSubclassOf(typeof(Delegate)) ?
$"{pi.ParameterType.Name}({string.Join(", ", pi.ParameterType.GetMethod("Invoke").GetParameters().Select(p = > p.ParameterType.Name))})" :
pi.ParameterType.Name
);
string methodNameWithParams = $"{method.Name}({string.Join(", ", parametersWithDelegateDetails)})";
return (true, $"{accessModifier} {returnType} {methodNameWithParams}");
}
}
D.在Program中添加一个方法和字段:
private static readonly int[] SequenceOrder = Base64StringToIntArray("AAAAAAAAAAACAAAAAwAAAAIAAAACAAAAAwAAAAQAAAACAAAAAgAAAAQAAAABAAAAAwAAAAAAAAACAAAAAwAAAAQAAAAAAAAAAgAAAAAAAAA=");
public static int[] Base64StringToIntArray(string base64String)
{
byte[] byteArray = Convert.FromBase64String(base64String);
int[] integerArray = ByteArrayToIntArray(byteArray);
return integerArray;
}
private static int[] ByteArrayToIntArray(byte[] byteArray)
{
int[] integerArray = new int[(byteArray.Length / sizeof(int))];
Buffer.BlockCopy(byteArray, 0, integerArray, 0, byteArray.Length);
return integerArray;
}
E.在Program类中Main方法添加如下代码:
var result = MethodAnalyzer.AnalyzeMethod("DoOperation", typeof(DisplayOnScreenMessageWithMethods));
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Silent (no audible sound, but may cause ripples in underground water sources)", DisplayOnScreenMessageWithMethods.SubterraneanHeatResistantCrustacean)} - {"Silent (no audible sound, but may cause ripples in underground water sources)SubterraneanHeatResistantCrustacean".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Silent (no audible sound, but may cause ripples in underground water sources)", DisplayOnScreenMessageWithMethods.SubterraneanHeatResistantCrustacean)} - {"Silent (no audible sound, but may cause ripples in underground water sources)SubterraneanHeatResistantCrustacean".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Mild clicking sounds (during feeding)", DisplayOnScreenMessageWithMethods.UnderwaterSpongeFeedingFish)} - {"Mild clicking sounds (during feeding)UnderwaterSpongeFeedingFish".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Soft tapping sounds (as they move across the snow surface)", DisplayOnScreenMessageWithMethods.ArcticSurfaceForagingArthropod)} - {"Soft tapping sounds (as they move across the snow surface)ArcticSurfaceForagingArthropod".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Mild clicking sounds (during feeding)", DisplayOnScreenMessageWithMethods.UnderwaterSpongeFeedingFish)} - {"Mild clicking sounds (during feeding)UnderwaterSpongeFeedingFish".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Mild clicking sounds (during feeding)", DisplayOnScreenMessageWithMethods.UnderwaterSpongeFeedingFish)} - {"Mild clicking sounds (during feeding)UnderwaterSpongeFeedingFish".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Soft tapping sounds (as they move across the snow surface)", DisplayOnScreenMessageWithMethods.ArcticSurfaceForagingArthropod)} - {"Soft tapping sounds (as they move across the snow surface)ArcticSurfaceForagingArthropod".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Electric crackling sounds (when producing electric shocks)", DisplayOnScreenMessageWithMethods.UnderwaterElectricGenerator)} - {"Electric crackling sounds (when producing electric shocks)UnderwaterElectricGenerator".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Mild clicking sounds (during feeding)", DisplayOnScreenMessageWithMethods.UnderwaterSpongeFeedingFish)} - {"Mild clicking sounds (during feeding)UnderwaterSpongeFeedingFish".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Mild clicking sounds (during feeding)", DisplayOnScreenMessageWithMethods.UnderwaterSpongeFeedingFish)} - {"Mild clicking sounds (during feeding)UnderwaterSpongeFeedingFish".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Electric crackling sounds (when producing electric shocks)", DisplayOnScreenMessageWithMethods.UnderwaterElectricGenerator)} - {"Electric crackling sounds (when producing electric shocks)UnderwaterElectricGenerator".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Soft glowing pulses (bioluminescent display)", DisplayOnScreenMessageWithMethods.MarineIlluminatingJellyfish)} - {"Soft glowing pulses (bioluminescent display)MarineIlluminatingJellyfish".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Soft tapping sounds (as they move across the snow surface)", DisplayOnScreenMessageWithMethods.ArcticSurfaceForagingArthropod)} - {"Soft tapping sounds (as they move across the snow surface)ArcticSurfaceForagingArthropod".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Silent (no audible sound, but may cause ripples in underground water sources)", DisplayOnScreenMessageWithMethods.SubterraneanHeatResistantCrustacean)} - {"Silent (no audible sound, but may cause ripples in underground water sources)SubterraneanHeatResistantCrustacean".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Mild clicking sounds (during feeding)", DisplayOnScreenMessageWithMethods.UnderwaterSpongeFeedingFish)} - {"Mild clicking sounds (during feeding)UnderwaterSpongeFeedingFish".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Soft tapping sounds (as they move across the snow surface)", DisplayOnScreenMessageWithMethods.ArcticSurfaceForagingArthropod)} - {"Soft tapping sounds (as they move across the snow surface)ArcticSurfaceForagingArthropod".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Electric crackling sounds (when producing electric shocks)", DisplayOnScreenMessageWithMethods.UnderwaterElectricGenerator)} - {"Electric crackling sounds (when producing electric shocks)UnderwaterElectricGenerator".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Silent (no audible sound, but may cause ripples in underground water sources)", DisplayOnScreenMessageWithMethods.SubterraneanHeatResistantCrustacean)} - {"Silent (no audible sound, but may cause ripples in underground water sources)SubterraneanHeatResistantCrustacean".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Mild clicking sounds (during feeding)", DisplayOnScreenMessageWithMethods.UnderwaterSpongeFeedingFish)} - {"Mild clicking sounds (during feeding)UnderwaterSpongeFeedingFish".TransformTo32Chars(result.MethodSignature)}");
Console.WriteLine($"{DisplayOnScreenMessageWithMethods.DoOperation("Silent (no audible sound, but may cause ripples in underground water sources)", DisplayOnScreenMessageWithMethods.SubterraneanHeatResistantCrustacean)} - {"Silent (no audible sound, but may cause ripples in underground water sources)SubterraneanHeatResistantCrustacean".TransformTo32Chars(result.MethodSignature)}");
Console.ReadLine();
运行程序,返回结果为: 1
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Soft tapping sounds (as they move across the snow surface) - EABF8A1DB64BD82CF2E6FF6F76937304
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Soft tapping sounds (as they move across the snow surface) - EABF8A1DB64BD82CF2E6FF6F76937304
Electric crackling sounds (when producing electric shocks) - 645D9F82174194CFBB312955C6B6496F
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Electric crackling sounds (when producing electric shocks) - 645D9F82174194CFBB312955C6B6496F
Soft glowing pulses (bioluminescent display) - E982491C04890A3CE2DD518F509284AA
Soft tapping sounds (as they move across the snow surface) - EABF8A1DB64BD82CF2E6FF6F76937304
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Soft tapping sounds (as they move across the snow surface) - EABF8A1DB64BD82CF2E6FF6F76937304
Electric crackling sounds (when producing electric shocks) - 645D9F82174194CFBB312955C6B6496F
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Soft tapping sounds (as they move across the snow surface) - EABF8A1DB64BD82CF2E6FF6F76937304
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Soft tapping sounds (as they move across the snow surface) - EABF8A1DB64BD82CF2E6FF6F76937304
Electric crackling sounds (when producing electric shocks) - 645D9F82174194CFBB312955C6B6496F
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Electric crackling sounds (when producing electric shocks) - 645D9F82174194CFBB312955C6B6496F
Soft glowing pulses (bioluminescent display) - E982491C04890A3CE2DD518F509284AA
Soft tapping sounds (as they move across the snow surface) - EABF8A1DB64BD82CF2E6FF6F76937304
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Soft tapping sounds (as they move across the snow surface) - EABF8A1DB64BD82CF2E6FF6F76937304
Electric crackling sounds (when producing electric shocks) - 645D9F82174194CFBB312955C6B6496F
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
Mild clicking sounds (during feeding) - 3542198D19EAD282859892FC232D80A0
Silent (no audible sound, but may cause ripples in underground water sources) - 69F5EF80FE591B0CF9245691DB3F0187
具体解析
按照下列要求完成程序编写:
A.在名空间中编写继承下列接口ICopyable 的四个类:Department、Book、Assignment、Student,其中,ShallowCopy和DeepCopy分别是浅拷贝和深拷贝方法;
public interface ICopyable < T >
{
T ShallowCopy();
T DeepCopy();
}
B.在名空间中创建DynamicComposite类:
public class DynamicComposite < T1, T2, T3, T4 >
{
public T1 Component1 { get; set; }
public T2 Component2 { get; set; }
public T3 Component3 { get; set; }
public T4 Component4 { get; set; }
}
C.在Program类中添加下列方法:
public static string CompareObjects(object obj1, object obj2, string parentPath = "")
{
Type type = obj1.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var differences = new List < string > ();
foreach (var prop in properties)
{
var path = string.IsNullOrEmpty(parentPath) ? prop.Name : $"{parentPath}.{prop.Name}";
var value1 = prop.GetValue(obj1);
var value2 = prop.GetValue(obj2);
if (value1 == null && value2 == null)
continue;
else if (value1 == null || value2 == null)
differences.Add($"Path '{path}' differs - Obj1: '{value1}', Obj2: '{value2}'");
else if (value1.GetType() == typeof(string) && value2.GetType() == typeof(string))
{
string str1 = (string)value1;
string str2 = (string)value2;
if (str1 != str2)
differences.Add($"Path '{path}' differs - Obj1: '{str1}', Obj2: '{str2}'");
}
else if (value1.GetType().IsClass && value2.GetType().IsClass)
{
string nestedDiff = CompareObjects(value1, value2, path);
if (!string.IsNullOrEmpty(nestedDiff))
{
differences.Add(nestedDiff);
}
}
else if (!object.Equals(value1, value2))
differences.Add($"Path '{path}' differs - Obj1: '{value1}', Obj2: '{value2}'");
}
if (differences.Any())
return string.Join("\n", differences);
else
return string.IsNullOrEmpty(parentPath) ? $"The {type.Name} objects are identical." : $"The {type.Name} objects at path '{parentPath}' are identical.";
}
public static string GenerateTypeStructureString(Type type)
{
StringBuilder outputBuilder = new StringBuilder();
HashSet < Type > processedTypes = new HashSet < Type > ();
Queue < Type > typesToProcess = new Queue < Type > ();
typesToProcess.Enqueue(type);
while (typesToProcess.Any())
{
Type currentType = typesToProcess.Dequeue();
if (processedTypes.Contains(currentType)) continue;
processedTypes.Add(currentType);
if (currentType.IsGenericType && !currentType.IsGenericTypeDefinition)
{
string genericTypeName = $"{currentType.Name.Split('`')[0]} < {string.Join(", ", currentType.GetGenericArguments().Select(a = > a.Name))} > ";
outputBuilder.Append($"类(Class):{genericTypeName}\n");
}
else
outputBuilder.Append($"类(Class):{currentType.Name.TrimStart('`')}\n");
AppendMembers(outputBuilder, currentType, "属性(Properties):", currentType.GetProperties(BindingFlags.Public | BindingFlags.Instance));
AppendMembers(outputBuilder, currentType, "字段(Fields):", currentType.GetFields(BindingFlags.Public | BindingFlags.Instance));
AppendMembers(outputBuilder, currentType, "方法(Methods):", currentType.GetMethods(BindingFlags.Public | BindingFlags.Instance));
foreach (var prop in currentType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
ProcessPropertyOrParameterType(prop.PropertyType, typesToProcess, processedTypes);
foreach (var method in currentType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
foreach (var parameter in method.GetParameters())
ProcessPropertyOrParameterType(parameter.ParameterType, typesToProcess, processedTypes);
}
return outputBuilder.ToString();
}
private static void ProcessPropertyOrParameterType(Type type, Queue < Type > typesToProcess, HashSet < Type > processedTypes)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List < > ))
{
Type elementType = type.GetGenericArguments()[0];
if (!IsBuiltInType(elementType) && !processedTypes.Contains(elementType))
typesToProcess.Enqueue(elementType);
}
else if (!IsBuiltInType(type) && !processedTypes.Contains(type))
typesToProcess.Enqueue(type);
}
private static bool IsBuiltInType(Type type) = > type.IsPrimitive || type.IsArray || type.IsAssignableFrom(typeof(Delegate)) || type.IsAssignableFrom(typeof(Enum)) || type.Namespace == "System" || type.Namespace.StartsWith("System.", StringComparison.Ordinal);
private static bool IsBuiltInMethod(MethodInfo methodInfo) = > methodInfo.IsSpecialName || methodInfo.DeclaringType == typeof(object);
private static void AppendMembers(StringBuilder outputBuilder, Type type, string memberTypeTitle, MemberInfo[] members)
{
if (members.Length > 0)
{
outputBuilder.Append($"{new string('\t', 1)}{memberTypeTitle}:\n");
foreach (var member in members)
{
string memberInfo;
if (member is PropertyInfo propertyInfo)
{
string typeName = GetReadableTypeName(propertyInfo.PropertyType);
memberInfo = $"{typeName} {propertyInfo.Name}";
outputBuilder.Append($"{new string('\t', 2)}-{memberInfo}\n");
}
else if (member is FieldInfo fieldInfo)
{
string typeName = GetReadableTypeName(fieldInfo.FieldType);
memberInfo = $"{typeName} {fieldInfo.Name}";
outputBuilder.Append($"{new string('\t', 2)}-{memberInfo}\n");
}
else if (member is MethodInfo methodInfo && !IsBuiltInMethod(methodInfo))
{
string returnType = GetReadableTypeName(methodInfo.ReturnType);
string methodName = methodInfo.Name;
string parametersStr = String.Join(", ", methodInfo.GetParameters().Select(p = >
GetReadableTypeName(p.ParameterType) + " " + p.Name));
memberInfo = $"{returnType} {methodName}({parametersStr})";
outputBuilder.Append($"{new string('\t', 2)}-{memberInfo}\n");
}
else
continue;
}
}
}
private static string GetReadableTypeName(Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List < > ))
{
Type genericArg = type.GetGenericArguments()[0];
return $"List < {GetReadableTypeName(genericArg)} > ";
}
else if (type.IsArray)
return $"{GetReadableTypeName(type.GetElementType())}[]";
else
return type.Name;
}
D.在名空间中,添加如下类:
public static class StringTransformer
{
public static string TransformTo32Chars(this string input, string key = "your-secret-key")
{
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(input));
string hashInHex = BitConverter.ToString(hashBytes).Replace("-", "");
return hashInHex.Substring(0, 32);
}
}
}
E.在Program类中的Main方法中,添加如下代码:
Console.WriteLine("Deep copied properties: Component1, Component4. Shallow copied properties: Component2, Component3.");
//按以下信息定义第一个DynamicComposite实例并给实例composite1赋值:
//DynamicComposite`4 = new DynamicComposite`4{Component1 = Department = new Department{DeptName = '08X8abQfoc', Building = 'TuoT04LA7s'}, Component2 = Book = new Book{Title = 'V1j46IJm5T', Author = 'oqWRCTDbKQ'}, Component3 = Assignment = new Assignment{Title = '8qHHc7iBUV', DueDate = DateTime.Now}, Component4 = Student = new Student{StudentId = 'SAhV9YcBSR', Name = 'okVxnYWQg0'}}
//定义第二个DynamicComposite实例composite2,四个属性分别为:composite1对象的Component2, Component3属性使用浅拷贝,composite1对象的Component1、Component4属性使用深拷贝
//把composite1对象Component2属性下的Title属性值修改成u0rtotbb9j
Console.WriteLine("Randomly selected inner property of Book: Title.
Successfully assigned 'u0rtotbb9j' to the property 'Title'.");
//使用CompareObjects方法比较两个DynamicComposite实例,并输出返回值
//把composite1对象Component3属性下的Title属性值修改成HRjAWqy6D4
Console.WriteLine("Randomly selected inner property of Assignment: Title.
Successfully assigned 'HRjAWqy6D4' to the property 'Title'.");
//使用CompareObjects方法比较两个DynamicComposite实例,并输出返回值
Console.WriteLine($"Key: {GenerateTypeStructureString(composite1.GetType()).Replace(" ", "").TransformTo32Chars("u0rtotbb9j")}");
Randomly selected inner property of Book: Title.Successfully assigned 'u0rtotbb9j' to the property 'Title'.
Randomly selected inner property of Assignment: Title.Successfully assigned 'HRjAWqy6D4' to the property 'Title'.
Key: 1DAACD06B79B3ADDB22B3CC547633A1C
Deep copied properties: Component1, Component4. Shallow copied properties: Component2, Component3.
Randomly selected inner property of Book: Title.
Successfully assigned 'u0rtotbb9j' to the property 'Title'.
The Department objects at path 'Component1' are identical.
The Book objects at path 'Component2' are identical.
The Assignment objects at path 'Component3' are identical.
The Student objects at path 'Component4' are identical.
Randomly selected inner property of Assignment: Title.
Successfully assigned 'HRjAWqy6D4' to the property 'Title'.
The Department objects at path 'Component1' are identical.
The Book objects at path 'Component2' are identical.
The Assignment objects at path 'Component3' are identical.
The Student objects at path 'Component4' are identical.
Key: 1DAACD06B79B3ADDB22B3CC547633A1C
具体解析
根据下述步骤要求,编写表达式体编写构造函数和ToString():
①选择Visual Studio工具栏中的“文件”->“新建”->“项目”命令,打开“新建项目”对话框;
②选择“控制台应用(.Net Framework)”
③输入任意项目名称,选择保存位置,确定完成创建;
④打开Program.cs文件,这里给出一个使用表达式体编写的类的模板,按以下要求编写代码:
class User
{
private string Name;
private string Occupation;
public User(string name, string occupation) = >
(this.Name, this.Occupation) = (name, occupation);
public override string ToString() = >
$"User {{ {this.Name} {this.Occupation} }}";
}
A.增加一个台灯的类,类名为DeskLamp,该类DeskLamp中含有4个私有字段,字段名为LightSourceType、AdjustmentMethod、ColorTemperature、ColorRenderingIndex,请用单行命令定义所有的字段,该类含有4个整型参数的构造函数,参数变量分别为lightsourcetype、adjustmentmethod、colortemperature、colorrenderingindex,其功能是为4个字段分别赋值;同样该类需要重写ToString()方法,以“User { {this.Name} {this.Occupation} }”方式输出类名和所有的字段值,中间用空格间隔;请使用表达式体编写出类DeskLamp的代码并填入 1 ;
B.增加一个空调的类,类名为AirConditioner,该类AirConditioner中含有4个私有字段,字段名为Capacity、EnergyEfficiencyRating、CoolingCapacity、HeatingCapacity,请用单行命令定义所有的字段,该类含有4个整型参数的构造函数,参数变量分别为capacity、energyefficiencyrating、coolingcapacity、heatingcapacity,其功能是为4个字段分别赋值;同样该类需要重写ToString()方法,以“User { {this.Name} {this.Occupation} }”方式输出类名和所有的字段值,中间用空格间隔;请使用表达式体编写出类AirConditioner的代码并填入 2 ;
C.模仿User类编写一个Community类,添加4个字段,分别是字符串类型字段Name、Occupation,DeskLamp类型字段desklamp,AirConditioner类型字段airconditioner,每个字段单独一行命令定义,该类含有4个整型参数的构造函数,参数变量分别为name、occupation、desklamp、airconditioner,其功能是为4个字段分别赋值;同样该类需要重写ToString()方法,以“User { {this.Name} {this.Occupation} }”方式输出类名和所有的字段值,中间用空格间隔;请使用表达式体编写出类Community的代码并填入 3 ;
⑤Program.cs文件中的Main方法中,按以下要求编写代码:
//使用表达式体对Community类的实例community进行实例化;
//其中,Name的值是佟信的大写全拼,Occupation=Roofer
//DeskLamp实例属性:LightSourceType, AdjustmentMethod, ColorTemperature, ColorRenderingIndex,分别赋值4, 9, 8, 6
//AirConditioner实例属性:Capacity, EnergyEfficiencyRating, CoolingCapacity, HeatingCapacity,分别赋值4, 3, 2, 8
var community = 4 ; //请用非表达式体书写命令行
Console.WriteLine($"{Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{community}"))}");
⑥运行该程序。
请问该程序运行结果为 5 。
class DeskLamp
{
private int LightSourceType;
private int AdjustmentMethod;
private int ColorTemperature;
private int ColorRenderingIndex;
public DeskLamp(int lightsourcetype, int adjustmentmethod, int colortemperature, int colorrenderingindex) =>
(this.LightSourceType, this.AdjustmentMethod, this.ColorTemperature, this.ColorRenderingIndex) = (lightsourcetype, adjustmentmethod, colortemperature, colorrenderingindex);
public override string ToString() =>
$"DeskLamp {{ {this.LightSourceType} {this.AdjustmentMethod} {this.ColorTemperature} {this.ColorRenderingIndex} }}";
}
class AirConditioner
{
private int Capacity;
private int EnergyEfficiencyRating;
private int CoolingCapacity;
private int HeatingCapacity;
public AirConditioner(int capacity, int energyefficiencyrating, int coolingcapacity, int heatingcapacity) =>
(this.Capacity, this.EnergyEfficiencyRating, this.CoolingCapacity, this.HeatingCapacity) = (capacity, energyefficiencyrating, coolingcapacity, heatingcapacity);
public override string ToString() =>
$"AirConditioner {{ {this.Capacity} {this.EnergyEfficiencyRating} {this.CoolingCapacity} {this.HeatingCapacity} }}";
}
class Community
{
private string Name;
private string Occupation;
private DeskLamp desklamp;
private AirConditioner airconditioner;
public Community(string name, string occupation, DeskLamp desklamp, AirConditioner airconditioner) =>
(this.Name, this.Occupation, this.desklamp, this.airconditioner) = (name, occupation, desklamp, airconditioner);
public override string ToString() =>
$"Community {{ {this.Name} {this.Occupation} {this.desklamp} {this.airconditioner} }}";
}
class DeskLamp
{
private int LightSourceType, AdjustmentMethod, ColorTemperature, ColorRenderingIndex;
public DeskLamp(int lightsourcetype, int adjustmentmethod, int colortemperature, int colorrenderingindex) =>
(this.LightSourceType, this.AdjustmentMethod, this.ColorTemperature, this.ColorRenderingIndex) = (lightsourcetype, adjustmentmethod, colortemperature, colorrenderingindex);
public override string ToString() =>
$"DeskLamp {{ {this.LightSourceType} {this.AdjustmentMethod} {this.ColorTemperature} {this.ColorRenderingIndex} }}";
}
class AirConditioner
{
private int Capacity, EnergyEfficiencyRating, CoolingCapacity, HeatingCapacity;
public AirConditioner(int capacity, int energyefficiencyrating, int coolingcapacity, int heatingcapacity) =>
(this.Capacity, this.EnergyEfficiencyRating, this.CoolingCapacity, this.HeatingCapacity) = (capacity, energyefficiencyrating, coolingcapacity, heatingcapacity);
public override string ToString() =>
$"AirConditioner {{ {this.Capacity} {this.EnergyEfficiencyRating} {this.CoolingCapacity} {this.HeatingCapacity} }}";
}
class Community
{
private string Name;
private string Occupation;
private DeskLamp desklamp;
private AirConditioner airconditioner;
public Community(string name, string occupation, DeskLamp desklamp, AirConditioner airconditioner) =>
(this.Name, this.Occupation, this.desklamp, this.airconditioner) = (name, occupation, desklamp, airconditioner);
public override string ToString() =>
$"Community {{ {this.Name} {this.Occupation} {this.desklamp} {this.airconditioner} }}";
}
具体解析Community { TONGXIN Roofer DeskLamp { 4 9 8 6 } AirConditioner { 4 3 2 8 } }
根据下述步骤要求,编写对象初始化和重写ToString():
①选择Visual Studio工具栏中的“文件”->“新建”->“项目”命令,打开“新建项目”对话框;
②选择“控制台应用(.Net Framework)”
③输入任意项目名称,选择保存位置,确定完成创建;
④打开Program.cs文件,按以下要求编写代码:
A.增加一个电饭煲的类,类名为:RiceCooker,添加4个字段,字段名为Capacity、InnerPotMaterial、Function、ControlMethod;
B.增加一个书柜的类,类名为:Bookcase,添加4个字段,字段名为Material、Size、NumberofShelves、Style;
C.增加一个Father类,添加4个字段,分别是字符串类型字段Name、Job,RiceCooker类型字段ricecooker,(属性:Capacity = 39,InnerPotMaterial = 31,Function = 35,ControlMethod = 48),Bookcase类型字段bookcase,(属性:Material = 25,Size = 10,NumberofShelves = 24,Style = 15);
D.重写Father类的ToString()方法,使它返回$"{Name},{Job},{ricecooker.Capacity},{ricecooker.InnerPotMaterial},{ricecooker.Function},{ricecooker.ControlMethod},{bookcase.Material},{bookcase.Size},{bookcase.NumberofShelves},{bookcase.Style}";
⑤Program.cs文件中的Main方法中,按以下要求编写代码:
//以单行语句对Father类的实例father进行实例化;
//其中:Name的值是岳福昭的大写全拼,Occupation=Optician,RiceCooker类型字段ricecooker,(属性:Capacity = 39,InnerPotMaterial = 31,Function = 35,ControlMethod = 48),Bookcase类型字段bookcase,(属性:Material = 25,Size = 10,NumberofShelves = 24,Style = 15),
1
Console.WriteLine($"{Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{father}"))}");
⑥运行该程序。
请问该程序运行结果为 2 。
Father father = new Father
{
Name = "YUEFUZHAO",
Job = "Optician",
ricecooker = new RiceCooker { Capacity = 39,InnerPotMaterial = 31,Function = 35,ControlMethod = 48 },
bookcase = new Bookcase { Material = 25,Size = 10,NumberofShelves = 24,Style = 15 }
};
具体解析
按要求编写一个简单的委托程序:
A.声明名为RenderMessageBoxText无返回值无参数的委托;
B.定义5个匿名委托的方法,方法输出下列表格中的输出文字,如下表:
匿名委托名 |
输出文字 |
ArcticAuroraBorealisInspiredBird |
Glowing flight patterns (for attracting mates and territorial display) |
DesertDuneCarnivorousPlant |
Silent (no audible sound, but has passive trapping mechanisms) |
HighAltitudeAerialPredatorBird |
Screeching calls (to locate prey or defend territory) |
TropicalRainforestCanopyGliderMarsupial |
Soft vocalizations or clicks (for social interactions and territory defense) |
TerrestrialReptilianHerbivore |
Low-frequency rumbles (territorial display) |
C.在Program中添加一个方法和字段:
private static readonly int[] OrderArray = Base64StringToIntArray("AQAAAAIAAAAAAAAAAwAAAAQAAAA=");
private static readonly int[] SequenceOrder = Base64StringToIntArray("AAAAAAAAAAAAAAAAAgAAAAQAAAABAAAAAwAAAAAAAAADAAAABAAAAAAAAAACAAAAAgAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAwAAAAEAAAA=");
////////////////////////////
// 此处需要定义匿名委托 //
////////////////////////////
private static readonly RenderMessageBoxText[] rendermessageboxtexts = { ArcticAuroraBorealisInspiredBird, DesertDuneCarnivorousPlant, HighAltitudeAerialPredatorBird, TropicalRainforestCanopyGliderMarsupial, TerrestrialReptilianHerbivore };
public static void ExecuteBellsBySequence()
{
foreach (int index in SequenceOrder)
rendermessageboxtexts[index]();
}
public static string GetBellActionNamesInOrderAsString()
{
Type thisType = typeof(Program);
FieldInfo[] fields = thisType.GetFields(BindingFlags.Public | BindingFlags.Static);
var bellActionsWithIndexes = fields
.Where(field = > field.FieldType == typeof(RenderMessageBoxText))
.Select((field, index) = > (Name: field.Name, Index: index))
.ToDictionary(pair = > pair.Index, pair = > pair.Name);
var outputBuilder = new StringBuilder();
foreach (int index in OrderArray)
if (bellActionsWithIndexes.ContainsKey(index))
outputBuilder.AppendLine(bellActionsWithIndexes[index]);
else
outputBuilder.AppendLine($"Warning: No BellAction found for the given order index {index}");
return outputBuilder.ToString();
}
public static int[] Base64StringToIntArray(string base64String)
{
byte[] byteArray = Convert.FromBase64String(base64String);
int[] integerArray = ByteArrayToIntArray(byteArray);
return integerArray;
}
private static int[] ByteArrayToIntArray(byte[] byteArray)
{
int[] integerArray = new int[(byteArray.Length / sizeof(int))];
Buffer.BlockCopy(byteArray, 0, integerArray, 0, byteArray.Length);
return integerArray;
}
D.在Program类中Main方法添加如下代码:
ExecuteBellsBySequence();
string orderedBellActionNames = GetBellActionNamesInOrderAsString();
Console.WriteLine(orderedBellActionNames);
Console.ReadLine();
运行程序,返回结果为: 1
Glowing flight patterns (for attracting mates and territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Screeching calls (to locate prey or defend territory)
Low-frequency rumbles (territorial display)
Silent (no audible sound, but has passive trapping mechanisms)
Soft vocalizations or clicks (for social interactions and territory defense)
Glowing flight patterns (for attracting mates and territorial display)
Soft vocalizations or clicks (for social interactions and territory defense)
Low-frequency rumbles (territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Screeching calls (to locate prey or defend territory)
Screeching calls (to locate prey or defend territory)
Glowing flight patterns (for attracting mates and territorial display)
Low-frequency rumbles (territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Low-frequency rumbles (territorial display)
Soft vocalizations or clicks (for social interactions and territory defense)
Silent (no audible sound, but has passive trapping mechanisms)
Warning: No BellAction found for the given order index 1
Warning: No BellAction found for the given order index 2
Warning: No BellAction found for the given order index 0
Warning: No BellAction found for the given order index 3
Warning: No BellAction found for the given order index 4
Glowing flight patterns (for attracting mates and territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Screeching calls (to locate prey or defend territory)
Low-frequency rumbles (territorial display)
Silent (no audible sound, but has passive trapping mechanisms)
Soft vocalizations or clicks (for social interactions and territory defense)
Glowing flight patterns (for attracting mates and territorial display)
Soft vocalizations or clicks (for social interactions and territory defense)
Low-frequency rumbles (territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Screeching calls (to locate prey or defend territory)
Screeching calls (to locate prey or defend territory)
Glowing flight patterns (for attracting mates and territorial display)
Low-frequency rumbles (territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Glowing flight patterns (for attracting mates and territorial display)
Low-frequency rumbles (territorial display)
Soft vocalizations or clicks (for social interactions and territory defense)
Silent (no audible sound, but has passive trapping mechanisms)
DesertDuneCarnivorousPlant
HighAltitudeAerialPredatorBird
ArcticAuroraBorealisInspiredBird
TropicalRainforestCanopyGliderMarsupial
TerrestrialReptilianHerbivore
具体解析
设计一个基类Animal,其中包含两个string类型属性:ChineseName和EnglishName,用于输入属性值的构造函数,另外有一个虚方法Show(),解决输出问题,另外创建一个类Featrue:
// 定义动物项类 (Animal)
public class Animal
{
// 中文名称属性
string ChineseName { get; set; }
// 英文名称属性
string EnglishName { get; set; }
// 构造函数,初始化动物项时设置中文名、英文名及特点
public Animal(string chineseName, string englishName)
{
ChineseName = chineseName;
EnglishName = englishName;
}
public virtual void Show()
{
Console.WriteLine($"中文名:{ChineseName}");
Console.WriteLine($"英文名:{EnglishName}");
}
}
创建两个类ElectricEel和BrushtailedPossum,分别定义动物电鳗和帚尾袋貂的类,其中中文名和英文名继承自基类Animal,它们都有一个Feature类型的属性Characteristics,用于描述动物电鳗和帚尾袋貂的特点,这其中Feature类的定义如下:
public class Feature
{
public string[] UniqueTraits { get; set; }
public Feature(params string[] uniqueTraits)
{
UniqueTraits = uniqueTraits;
}
}
Main方法的代码如下:
ElectricEel electriceel = new ElectricEel("电鳗", "ElectricEel", "亚马逊流域的淡水鱼,能产生强烈电流", "身体细长,能连续释放电压高达600伏特的电击", "肉食性,以鱼类、水生无脊椎动物为食");
BrushtailedPossum brushtailedpossum = new BrushtailedPossum("帚尾袋貂", "BrushtailedPossum", "澳大利亚特有的有袋类哺乳动物", "善于攀爬,拥有长而浓密的尾巴", "夜间活动,主要以树叶、果实、花蜜和昆虫为食");
electriceel.Show();
brushtailedpossum.Show();
Console.ReadLine();
请把你定义的ElectricEel类,写在 1 内,BrushtailedPossum类,写在 2 内,类中有一个Feature类型的属性Characteristics,构造函数中需要添加一个特点uniqueTraits的参数,类型为params string[],同时在基类输出的基础上增加一个特点的输出,如:特点:特点1, 特点2, 特点3;
运行程序,运行结果为: 3
public class ElectricEel : Animal
{
Feature Characteristics { get; set; }
public ElectricEel(string chineseName, string englishName, params string[] uniqueTraits)
: base(chineseName, englishName)
{
Characteristics = new Feature(uniqueTraits);
}
public override void Show()
{
base.Show();
Console.WriteLine($"特点:{string.Join(", ", Characteristics.UniqueTraits)}");
}
}
public class BrushtailedPossum : Animal
{
Feature Characteristics { get; set; }
public BrushtailedPossum(string chineseName, string englishName, params string[] uniqueTraits)
: base(chineseName, englishName)
{
Characteristics = new Feature(uniqueTraits);
}
public override void Show()
{
base.Show();
Console.WriteLine($"特点:{string.Join(", ", Characteristics.UniqueTraits)}");
}
}
中文名:电鳗
英文名:ElectricEel
特点:亚马逊流域的淡水鱼,能产生强烈电流, 身体细长,能连续释放电压高达600伏特的电击, 肉食性,以鱼类、水生无脊椎动物为食
中文名:帚尾袋貂
英文名:BrushtailedPossum
特点:澳大利亚特有的有袋类哺乳动物, 善于攀爬,拥有长而浓密的尾巴, 夜间活动,主要以树叶、果实、花蜜和昆虫为食
public class ElectricEel : Animal
{
Feature Characteristics { get; set; }
public ElectricEel(string chineseName, string englishName, params string[] uniqueTraits) : base(chineseName, englishName)
{
Characteristics = new Feature(uniqueTraits);
}
public override void Show()
{
base.Show();
Console.WriteLine($"特点:{string.Join(", ",Characteristics.UniqueTraits)}");
}
}
public class BrushtailedPossum : Animal
{
Feature Characteristics { get; set; }
public BrushtailedPossum(string chineseName, string englishName, params string[] uniqueTraits) : base(chineseName, englishName)
{
Characteristics = new Feature(uniqueTraits);
}
public override void Show()
{
base.Show();
Console.WriteLine($"特点:{string.Join(", ",Characteristics.UniqueTraits)}");
}
}
中文名:电鳗
英文名:Electric Eel
特点:亚马逊流域的淡水鱼,能产生强烈电流,身体细长,能连续释放电压高达600伏特的电击,肉食性,以鱼类、水生无脊椎动物为食
中文名:帚尾袋貂
英文名:Brush tailed Possum
特点:澳大利亚特有的有袋类哺乳动物,善于攀爬,拥有长而浓密的尾巴,夜间活动,主要以树叶、果实、花蜜和昆虫为食
具体解析