简体   繁体   中英

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

GetPlayerProfiles(TeamPlayersLandingPage teamPlayersPage)
GetStaffProfiles(TeamStaffLandingPage staffMembersPage)

Within each of the above methods i create a SponsorListItem to associate a sponsor with the profile. 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.

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)

在此处输入图像描述

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:

public class TeamPlayersLandingPage : ISponsor
{
}

Now you can constrain your generic method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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