1.有两个实体类,分别如下:
class User
{
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
}
class Demo
{
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
}
2.泛型方法:
/// <summary>
/// 判断两个相同类型的对象的属性值是否相等
/// 如果不相等则返回不相等的字段名,否则返回空字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj1"></param>
/// <param name="obj2"></param>
/// <returns></returns>
private static bool CompareProperties<T>(T obj1, T obj2)
{
//为空判断
if (obj1 == null && obj2 == null)
{
return true;
}
else if (obj1 == null || obj2 == null)
{
return false;
}
PropertyInfo[] properties = obj1.GetType().GetProperties();
foreach (var po in properties)
{
if (!po.GetValue(obj1, null).Equals(po.GetValue(obj2, null)))
{
return false;
}
}
return true;
}
3.调用2中的方法出错:
User user = new User
{
Age = 20
};
Demo demo = new Demo
{
Age = 20
};
//下一行代码报错:无法从用法中推导出方法“CommandLineTest.Program.CompareProperties<T>(T, T)”的类型实参。请尝试显式指定类型实参。
bool compareResult = CompareProperties(user, demo);
4.如果传入相同类型的变量就运行正常,比如:
bool compareResult = CompareProperties(user1, user2);
如果需要接受两个不同类型的参数,
CompareProperties
方法需要定义成如下形式: