开发者

Why do some .NET Framework classes not use Generics when they could?

开发者 https://www.devze.com 2022-12-30 07:43 出处:网络
Example: System.Web.Security.MembershipCollection implements IEnumerable and not IEnumberable<T>. Why doesn\'t it implement the latter, when it seems that it would be better (e.g. use LINQ)?

Example:

System.Web.Security.MembershipCollection implements IEnumerable and not IEnumberable<T>. Why doesn't it implement the latter, when it seems that it would be better (e.g. use LINQ)?

Or, 开发者_JAVA百科is it not necessarily better?


History matters. Generics didn't always exist, so you may encounter classes and APIs that were designed before the advent of generics.

Also, target audience matters. Some features are targeting a developer audience that may have problems understanding generics:

Tradeoff: APIs using some advanced features of Generics may be too difficult to use for some developers. The concept of Generics is not widely understood, in some cases the syntax may pose problems, and as any large new feature, Generics may pose a significant learning curve for some entry-level developers.

Yes, the quote is from 2004, but some, if not most of the .Net API you use today came out in 2005, so the quote is actually very relevant.


You can use LINQ with any IEnumerable by using the Cast<T>() function or the OfType<T>() function. If you're confident that the IEnumerable only contains objects of a particular type, then Cast<T>() will be slightly faster.

For example,

ArrayList foo = new ArrayList();

foo.Add("bar");
foo.Add("baz");

var bar = foo.Cast<string>().Select(s => s.ToUpper());

There are many existing classes (like ArrayList) that existed before the advent of generics in .NET, so they are still non-generic.


These classes often date from before there were generics in .net many such classes have generic equievelents but not all. There are also workarounds. e.g. with linq any non generic collections can be made linqy and generic using the .Cast() and .OfType() extension methods.


Keep in mind that many of the BCL types we're using are from the time before generics, which arrived in 2.0. However, you can still use LINQ with many of them, you simply have to do a little extra work.

ArrayList arrayList = new ArrayList();
arrayList.Add(1);
arrayList.Add(2);

var query = from item in arrayList.OfType<int>() select item;
0

精彩评论

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

关注公众号