gpt4 book ai didi

C# IComparable 与 1 parent 2 children

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:47 25 4
gpt4 key购买 nike

好吧,我有一个类 Human 实现了 IComparable<Human>

然后我还有两个继承自 Human Child:Human 和 Cousin:Human 的类

Parent 类有一个属性 AGE,在 getter 中有一个对抽象函数 getAge() 的调用。

我有一个人类列表,当我在数据网格中显示它们时,每个年龄都会被正确计算。

我想使用年龄作为属性对列表进行排序,所以我创建了 Human 抽象类来实现 Icomparable,然后是这样的方法。

public int CompareTo(Human other)
{
return this.age.CompareTo(other.age);
}

我调用 list.sort()像这样在 ASP 中的方法

List<Human> hlist = instance.humanlist;
hlist.Sort();
tblHumans.DataSource = hlist;
tblHumans.DataBind();

页面加载了所有数据,但项目不是按年龄排序的,它似乎是按列表中的位置排序的。

我的 tblHumans 是

<asp:GridView ID="tblHumans" runat="server">
</asp:GridView>

在Parent类中属性AGE是这样的

public int Age
{
get
{
return getAge();
}

set
{
age = getAge();
}
}

getAge() 是我的子类覆盖的抽象方法

计算是正确返回值,当呈现表格时,每个值都在那里,结果正确。

我做错了什么?

最佳答案

简答

public int CompareTo(Human other)
{
return this.Age.CompareTo(other.Age);
}

(年龄,不是年龄)

更长的答案

Age 属性的实现已损坏。您有一个 age 字段,但它的值未被 getter(仅调用 getAge())使用。并且 setter 忽略隐式 value 参数,因此它只是将 age 分配给 getAge() 的结果。因此,虽然尚未调用 setter,但 age 未初始化且其值为 0。您可能根本不应该有 setter,并且应该删除 age 字段,因为 Age 的值仅由 getAge() 的实现决定。

关于C# IComparable 与 1 parent 2 children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42491669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com