c#泛型方法报错

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);
阅读 2k
1 个回答

如果需要接受两个不同类型的参数,CompareProperties 方法需要定义成如下形式:

private static bool CompareProperties<T1, T2>(T1 obj1, T2 obj2)
{
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进