简体   繁体   English

实现接口C#

[英]Implementing interface C#

I'm not new to C#, but I have found a behavior that is a little puzzling. 我不是C#的新手,但我发现了一个有点令人费解的行为。

I have an interface 我有一个界面

public interface IApplicationPage
{
    Person ThePerson { get; set;  }
    Application Application { get; set; }
}

I implement the interface on a page 我在页面上实现了界面

public partial class tripapplication2 : System.Web.UI.Page, IApplicationPage
{
    Person IApplicationPage.ThePerson { get; set; }
    Application IApplicationPage.IApplicationPage.Application { get; set; }
}

However, when I attempt to reference ThePerson in the page itself I need to jump through hoops. 但是,当我尝试在页面本身引用ThePerson时,我需要跳过箍。 For example. 例如。

1) ThePerson.Birthday 1)ThePerson.Birthday

Gives an error saying "The name 'ThePerson' does not exist in the current context." 提出错误说“当前上下文中不存在名称'ThePerson'。”

2) ((IMissionTripApplicationPage)this).ThePerson.Birthday 2)((IMissionTripApplicationPage)这个。)ThePerson.Birthday

This works, but it looks awful. 这有效,但看起来很糟糕。

Is there a better way to reference the implemented properties? 有没有更好的方法来引用已实现的属性?

It looks like you left a line out in your sample. 看起来你在样品中留下了一条线。 I believe the ThePerson line in the implementation should read 我相信实施中的ThePerson系列应该阅读

Person IApplicationPage.ThePerson { get; set; }

This type of implementation is known as an explicit interface implementation. 这种类型的实现称为显式接口实现。 This means the member will only be viewable when the object is seen through a reference of the interface type. 这意味着只有在通过接口类型的引用看到对象时才能查看该成员。

If you want the member to be viewable through a concrete type reference, make it public and remove the explicit implementation 如果希望通过具体类型引用查看成员,请将其公开并删除显式实现

public Person ThePerson { get; set; }

Implement them as public properties: 将它们实现为公共属性:

public partial class tripapplication2 : System.Web.UI.Page, IApplicationPage
{
    public Person ThePerson { get; set; }
    public Application IApplicationPage.Application { get; set; }
}

Edit 编辑

Question now edited to show these were implemented originally as explicit. 现在编辑的问题显示这些问题最初是作为显式实现的。 So, I should restate mine as implement them as public rather than explicit implementations of the properties. 所以,我应该重申我的实现它们作为公共而不是显式的属性实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM