Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. // So you want to use anonymous interface implementations in C#? Does this lambda-based usage look ok?
  2. // Ignore the fact that "list" and "projection" are undefined here, just note the lambdas that can close
  3. // around any variables and procedures you want.
  4.  
  5. new AnonymousReadOnlyList<TOut>(
  6. count: () => list.Count,
  7. item: i => projection(list[i]),
  8. iterator: list.AsEnumerable().Select(projection));
  9.  
  10. new AnonymousReadOnlyList<TOut>(
  11. count: () => list.Count,
  12. item: i => projection(list[i], i),
  13. iterator: list.AsEnumerable().Select(projection));
  14.  
  15. new AnonymousReadOnlyList<T>(
  16. count: () => list.Count,
  17. item: i => list[list.Count - 1 - i]);
  18.  
  19. new AnonymousReadOnlyList<TOut>(
  20. count: () => Math.Min(list1.Count, list2.Count),
  21. item: i => projection(list1[i], list2[i]),
  22. iterator: list1.AsEnumerable().Zip(list2, projection));
  23.  
  24. new AnonymousReadOnlyList<int>(
  25. count: () => count,
  26. item: i => i,
  27. iterator: Enumerable.Range(0, count));
  28.  
  29. // ... and so on. This is how:
  30.  
  31. // 1. Define your interface.
  32. public interface IReadOnlyList<out T> : IReadOnlyCollection<T> {
  33. T this[int index] { get; }
  34. }
  35.  
  36. // 2. Provide a single not-so-concrete implementation for all anonymous implementations to use.
  37. // This also shows how to provide "default methods" - GetEnumerator() here.
  38. public sealed class AnonymousReadOnlyList<T> : IReadOnlyList<T> {
  39. private readonly Func<int> _count;
  40. private readonly Func<int, T> _item;
  41. private readonly IEnumerable<T> _iterator;
  42.  
  43. public AnonymousReadOnlyList(Func<int> count, Func<int, T> item, IEnumerable<T> iterator = null) {
  44. if (count == null) throw new ArgumentNullException("count");
  45. if (item == null) throw new ArgumentNullException("item");
  46. this._count = count;
  47. this._item = item;
  48. this._iterator = iterator ?? DefaultIterator(count, item);
  49. }
  50. private static IEnumerable<T> DefaultIterator(Func<int> count, Func<int, T> item) {
  51. var n = count();
  52. for (var i = 0; i < n; i++)
  53. yield return item(i);
  54. }
  55.  
  56. public int Count {
  57. get {
  58. return _count();
  59. }
  60. }
  61. public T this[int index] {
  62. get {
  63. return _item(index);
  64. }
  65. }
  66. public IEnumerator<T> GetEnumerator() {
  67. return _iterator.GetEnumerator();
  68. }
  69. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
  70. return GetEnumerator();
  71. }
  72. }
  73.  
  74. // 3. Now you can create anonymous implementations with lambdas like the ones at the beginning of this gist!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement