简体   繁体   中英

C# Generic Search Helper

I am trying to rewrite a Search helper using generics instead of what I have below, two identical methods except for the type of list being passed in. When I add <T> to the class and then insert <T> into the Type declaration of each of the lists, I get the following error:

The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'ProjectName.Helpers.Extensions.AttributeExtensions.GetDescription(T)'

public class SearchFilterHelper
{
    public static SelectList GenreSelectList(List<GenreFilter> filters, int selectedValue = 0)
    {
        var GenreList = filters.Select(g => new { Value = g.ToString(), Description = g.GetDescription() });
        return new SelectList(GeneratedList, "Value", "Description", selectedValue.ToString());
    }

    public static SelectList PublisherSelectList(List<PublisherFilter> filters, int selectedValue = 0)
    {
        var GeneratedList = filters.Select(g => new { Value = g.ToString(), Description = g.GetDescription() });
        return new SelectList(GeneratedList, "Value", "Description", selectedValue.ToString());
    }
}

This is my first attempt at using Generics in a Helper and any help in understanding how to rewrite this is, as always, appreciated...

The GetDescription method you have applies the generic constraint that the generic argument be a struct . If you want to call that method from yours, you'll need to apply that same generic constraint.

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