通用扩展方法 [英] generic extension method

查看:78
本文介绍了通用扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照Rob Connery的店面视频系列并应用这些技术来从事这个mvc项目. 在过滤和扩展方法上,我开始重复很多自己,例如:

I am working on this mvc project following Rob Connery's storefront video series and applying the techniques. On the filtering and extensions methods, i started repeating myself a lot such as:

public static Sponsor WithID(this IQueryable<Sponsor>qry, int ID)
{
    return qry.SingleOrDefault(s => s.ID== ID);
}

public static Keyword WithID(this IQueryable<Keyword>qry,int ID)
{
    return qry.SingleOrDefault(s => s.ID== ID);
}
....

为防止这种情况,我尝试编写一个通用扩展名,如下所示:

To prevent this,I try to write a generic extension like this:

public static T WithID<T>(this IQueryable<T>qry,int ID)
{
    return qry.SingleOrDefault(s=>ID==ID);
}

但是s没有ID,那么您将如何解决呢?

however s does not have ID, so how would you solve this?

推荐答案

您将需要一个声明ID属性的接口,例如

You'll need an interface which declares an ID property, e.g.

public interface IInt32Identifiable
{
    public int ID { get; }
}

然后您可以编写:

public static T WithID<T>(this IQueryable<T> source, int id)
    where T : IInt32Identifiable
{
   return source.SingleOrDefault(s=> s.ID == id);
}

当然,您必须使所有适当的类都实现该接口-但这通常很容易;如果这些类是设计人员生成的,则可能要使用部分类.

Of course, you'll have to make all the appropriate classes implement the interface - but that's usually easy; if the classes are designer-generated you probably want to use partial classes.

这篇关于通用扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆