开发者

Working Generic Lists of Base Types and Inherited Types

开发者 https://www.devze.com 2022-12-20 16:55 出处:网络
Basically, I\'m using an ORM (specifically LLBLGen) that creates entity objects for all my tables. All these entity types inherit from a base class (or really a set of them). I want to create an exten

Basically, I'm using an ORM (specifically LLBLGen) that creates entity objects for all my tables. All these entity types inherit from a base class (or really a set of them). I want to create an extension method that accepts a List of the base class and returns some string but I want to pass in inherited types without explicitly casting.

For instance, I have a function like:

string GetString(List<EntityBase2> list); // also tried List<IEntityCore>, which the base class implements

And I want to pass it something like this:

List<ProductEntity> products = ... // populate it

string v = GetString(products);

But I get compiler errors.

How can I accomplish creating this helper method. I want to avoid casting if I can but if 开发者_高级运维this is the best way then at least I could would have some confirmation on that.


try this:

string GetString<T>(List<T> list) where T : IEntityCore {...}

that way you get a generic method that takes a list of objects which implement IEntityCore. there's no need to cast and the compiler will make sure that you pass in the right objects. works starting at framework 2.0.

0

精彩评论

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

关注公众号