鍍金池/ 問答/Java  C#  HTML/ c#泛型方法報錯

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.調(diào)用2中的方法出錯:

User user = new User
{
    Age = 20
};
Demo demo = new Demo
{
    Age = 20
};
//下一行代碼報錯:無法從用法中推導(dǎo)出方法“CommandLineTest.Program.CompareProperties<T>(T, T)”的類型實參。請嘗試顯式指定類型實參。
bool compareResult = CompareProperties(user, demo);

4.如果傳入相同類型的變量就運(yùn)行正常,比如:

bool compareResult = CompareProperties(user1, user2);
回答
編輯回答
假灑脫

如果需要接受兩個不同類型的參數(shù),CompareProperties 方法需要定義成如下形式:

private static bool CompareProperties<T1, T2>(T1 obj1, T2 obj2)
{
}
2017年3月11日 02:07