覆盖对象上的ToString以在DataBinding中使用

时间:2009-05-18 00:43:12

标签: asp.net data-binding

我在ASP.Net 2.0中使用Databinding,我遇到了Eval命令的问题。

我有一个我正在数据绑定的类,看起来像这样:

public class Address
{
   public string Street;
   public string City;
   public string Country;
   public new string ToString()
   {
      return String.Format("{0}, {1}, {2}", Street, City, Country);
   }
}

另一个类(我正在数据绑定的那个):

public class Situation
{
  public Address ObjAddress;
  public string OtherInformation;
}

现在,当我有数据绑定控件时,例如

<asp:DetailsView ID="dvSituation" DataSourceID="dataSourceThatPullsSituations" AutoGenerateRows="false"runat="server">
<EmptyDataTemplate>
    No situation selected
</EmptyDataTemplate>
<Fields>
   <asp:BoundField HeaderText="Other data" DataField="OtherInformation" />
   <asp:TemplateField>
       <HeaderTemplate>
           Address
       </HeaderTemplate>
       <ItemTemplate>
            <%-- This will work --%>
            <%# ((Situation)Container.DataItem).ObjAddress.ToString() %>
            <%-- This won't --%>
            <%# Eval("ObjAddress") %>
       </ItemTemplate>
   </asp:TemplateField>
</Fields>
</asp:DetailsView>

当此字段为Eval时,为什么不调用我的ToString()类?我只是在eval运行时得到类型名称。

3 个答案:

答案 0 :(得分:4)

而不是使用:

public new string ToString()

使用覆盖关键字:

public override string ToString()

答案 1 :(得分:1)

在ToString方法中使用override关键字而不是new

答案 2 :(得分:0)

所以我的印象是 new 关键字会覆盖实现,即使调用对象就好像它是超类一样:

e.g。

Address test = new Address();
Object aFurtherTest = test;
aFurtherTest.ToString();

需要我使用 new 关键字。这个关键字实际上做的是有效地创建一个与基类中定义的方法同名的方法。

因此,如果我在上面的例子中习惯使用 new 关键字,我会得到对象的ToString方法。换句话说,根据我将其视为(基类或子类)的类型,ToString方法将调用另一种方法。

显然我应该有RTFM ......