简体   繁体   English

使用 C# 泛型方法并使其成为强类型

[英]Working with C# generic method and making it strongly typed

I have two profile types which are:我有两种配置文件类型:

TeamPlayerPage.cs & TeamStaffMemberPage

In my code (which is an Umbraco solution) I have created two methods that get and build up a collection of profiles eg在我的代码(这是一个 Umbraco 解决方案)中,我创建了两种方法来获取和构建配置文件的集合,例如

GetPlayerProfiles(TeamPlayersLandingPage teamPlayersPage)
GetStaffProfiles(TeamStaffLandingPage staffMembersPage)

Within each of the above methods i create a SponsorListItem to associate a sponsor with the profile.在上述每个方法中,我创建了一个 SponsorListItem 以将赞助商与配置文件相关联。 Example below下面的例子

private SponsorListItem GetPlayerSponsor(TeamPlayerPage teamPlayerPage)
{
    if (teamPlayerPage.Sponsor == null)
        return null;

    var sponsorPage = teamPlayerPage.Sponsor as SponsorPage;

    var sponsor = new SponsorListItem()
    {
        Heading = sponsorPage.Heading,
        Url = sponsorPage.Url,
        ListingImgUrl = sponsorPage.Image != null ? sponsorPage.GetCropUrl("image", "360x152(listing)") : Global.PlaceholderImage.GenericListingItem,
        KeySponsor = sponsorPage.KeySponsor
    };

    return sponsor;
}

The sponsor logic is exactly the same for each type so i would like to create one generic method eg GetProfileSponsor(T profilePage) as opposed to two (see below) The goal is to be able to pass either aa TeamPlayerPage or TeamStaffMemberPage to a generic method and have it be strongly typed so i can access the properties on it.每种类型的赞助商逻辑完全相同,因此我想创建一个通用方法,例如 GetProfileSponsor(T profilePage) 而不是两个(见下文)目标是能够将 aa TeamPlayerPage 或 TeamStaffMemberPage 传递给通用方法并让它被强类型化,这样我就可以访问它的属性。

private SponsorListItem GetPlayerSponsor(TeamPlayerPage teamPlayerPage)
private SponsorListItem GetStaffSponsor(TeamStaffMemberPage staffMembersPage)

I created the following but i'm not quite sure how to make the T profilePage parameter strongly typed against what is passed in (if that is possible)我创建了以下内容,但我不太确定如何使 T profilePage 参数针对传入的内容进行强类型化(如果可能的话)

在此处输入图像描述

I have done some searching around but struggling to understand the concept a little.我已经做了一些搜索,但很难理解这个概念。 Can someone please point me into the right direction?有人可以指出我正确的方向吗?

Thank you谢谢

Paul保罗

To do this, both of your classes need to implement a common interface so you can constrain the method to that.为此,您的两个类都需要实现一个通用接口,以便您可以将方法约束到该接口。 For example:例如:

public interface ISponsor
{
    SponsorPage Sponsor { get; }
}

And then make your class implement that interface:然后让您的 class 实现该接口:

public class TeamPlayersLandingPage : ISponsor
{
}

Now you can constrain your generic method:现在你可以约束你的泛型方法:

private SponsorListItem GetProfileSponsor<T>(T profilePage)
    where T : ISponsor
{
    var sponsor = profilePage.Sponsor;
}

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

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