通用扩展方法

编程入门 行业动态 更新时间:2024-10-26 16:26:56
本文介绍了通用扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在按照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.

更多推荐

通用扩展方法

本文发布于:2023-11-05 18:58:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561598.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!