开发者

How to create a flexible extension method for generic lists?

开发者 https://www.devze.com 2022-12-13 08:07 出处:网络
I have 2 objects Project and License. They both inherit from the object Entity (abstract class). Now I have an extension method \"GetNewId\" that contains logic to get the next id in a list of entiti

I have 2 objects Project and License. They both inherit from the object Entity (abstract class).

Now I have an extension method "GetNewId" that contains logic to get the next id in a list of entiti开发者_如何转开发es.

I've defined this method as an extension method, but the problem is that List (which is also a list of entities) and List don't see this method.

I guess that this problem will occur with any generic list containing objects that inherit from the same base class.

Is there a solution for this problem?

edit: working in C#


What class/interface is your GetNewId() method an extension of?

If you make it an extension of IEnumerable<T> - where T is restricted to be derived from your Entity base class - you should be able to use the extension method on any collection like class containing Entity based objects:

public static GetNewId<T>(this IEnumerable<T> sequence) where T : Entity {
    // your implementation of GetNewId here
}

The Cast method (from System.Linq) is also defined on IEnumerable<T> (but on any type T, no restrictions), hence you can use it on your licenses instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消