Generic helper method c#
Can I create an automatic generic helper method? Let me explain.
This is how I do now:
item.slp_spot_lang_prop.GetAvailable<slp_spot_lang_prop>(Model.LanguageAlternatives).slp_title
And then I have this helper method
public static T GetAvailable<T>(this IEnumerable<ILanguageEntity> helper, IQueryable<langa_language_alternative> languageAlt)
{
return (T) helper.SingleOrDefault(d => d.LanguageId == languageAlt.Single(e => e.langa_sitent_id == (int)d.SiteEntityId && e.langa_entid == d.EntityId && e.langa_wantedlangid == Global.SiteInfo.LanguageID).langa_availablelangid);
}
What I want to be able to do is simply
item.slp_spot_lang_prop.GetAvailable(Model.LanguageAlternatives).slp_title
And something like:
public static GetAvailable(this IEnumerable<ILanguageEntity> helper, IQueryable<langa_language_alternative> languageAlt)
{
var type = helper.GetEnumerator().Current.GetType().BaseType;
return (type) helper.SingleOrDefault(d => d.LanguageId == languageAlt.Single(e => e.langa_sitent_id == (int)d.SiteEntityId && e.langa_entid == d.EntityId && e.langa_wantedlangid == Global.SiteInf开发者_运维百科o.LanguageID).langa_availablelangid);
}
I hope you understand what I mean. The returning type should be an singular of the IEnumerable<IlanguageEntity>
's basetype which in the example should be slp_spot_lang_prop.
The whole purpose is to get rid of the GetAvailable<type>()
and just have GetAvailable()
, since it is an helper method I know already the return type.
Have you tried using a constraint on the generic to specify the helper type (it's not a helper, but you know this)? Using the constraint forces T to be, derive from, or implement the constraint type, but allows the actual value of T to be induced from the argument instead of specified. In your previous declaration, it had no way to determine what T was since it was unrelated to any of the parameters.
public static T GetAvailable<T>(this IEnumerable<T> helper,
IQueryable<langa_language_alternative> languageAlt)
where T : ILanguageEntity
{
return (T) helper.SingleOrDefault(d => d.LanguageId == languageAlt.Single(e => e.langa_sitent_id == (int)d.SiteEntityId
&& e.langa_entid == d.EntityId
&& e.langa_wantedlangid == Global.SiteInfo.LanguageID).langa_availablelangid);
}
精彩评论