用 C# 语言编写一个名为 Max 的泛型方法,它接受 2 个参数并返回 2 个值中的较大者。应用约束以仅支持引用类型。针对将薪水作为 int 类型属性的 Employee 类对其进行测试。Max 应根据薪水比较两个员工实例并返回具有更高薪水的员工实例。这就是我所做的我应该如何继续......?
using System;
using System.Collections.Generic;
using System.Text;
namespace Generic_Max_of_Salary
{
class Program
{
static void Main(string[] args)
{
runtest();
}
public static void runtest()
{
Test_Maximum(new Employee { Salary = 10000 }, new Employee { Salary = 20000 }, new Employee { Salary = 20000 }, 1);
Test_Maximum(new Employee { Salary = 30000 }, new Employee { Salary = 20000 }, new Employee { Salary = 30000 }, 2);
Test_Maximum(new Employee { Salary = 10000 }, new Employee { Salary = 10000 }, new Employee { Salary = 10000 }, 3);
}
public static void Test_Maximum(Employee emp1, Employee emp2, Employee obtained_answer, int testcase)
{
Employee expected_answer = Maximum<Employee>(emp1, emp2);
if (CompareTo(obtained_answer, expected_answer))
{
Console.WriteLine("Test " + testcase + " Passed");
}
else
{
Console.WriteLine("Test " + testcase + " Failed");
}
}
public static T Maximum<T>(T emp1, T emp2)
{
if (emp1.Salary >= emp2.Salary)
{
return emp1;
}
else
{
return emp2;
}
}
public static bool CompareTo(Employee obtained_answer, Employee expected_answer)
{
if (obtained_answer.Salary == expected_answer.Salary)
{
return true;
}
else
{
return false;
}
}
}
class Employee
{
public int Salary { get; set; }
}
}