User loginNavigation |
Accumulating Types in C#PartI: Code: namespace TypePiling { using System.Text; using System; using System.IO; public static class Ex { public static Tuple<T, U> Glue<T, U>(this T t, U u) { return new Tuple<T, U> { First = t, Second = u }; } } public class Tuple<T, U> { public T First { get; set; } public U Second { get; set; } public override string ToString() { var result = new StringBuilder(); if (this.First != null) result.Append(string.Format("{0}", this.First.ToString())); if (this.Second != null) result.Append(string.Format(", {0}", this.Second.ToString())); return string.Format("{{ {0} }}", result.ToString().TrimStart(',').Trim()); } } public static class Test { public static void Test1() { var i = 10; var g0 = i.Glue("Hi"); var g1 = g0.Glue((byte)0xFF); var g2 = g1.Glue(100.0); var g3 = g2.Glue('A'); var g4 = g3.Glue((float)1000); using (var sw = new StreamWriter("output.txt")) { sw.WriteLine(g0); sw.WriteLine(g1); sw.WriteLine(g2); sw.WriteLine(g3); sw.WriteLine(g4); sw.Flush(); } System.Diagnostics.Process.Start("output.txt"); } } }
This code does what I want and g4 will be: This is my first problem; as you see I do that by put previous value and next value in a new container. So previous values are pile down in First. I want them be piled up in Second, so g4 should be: I it possible in C# 3.5? If not why? Part II: public static Tuple<T, Tuple<U, V>> Glue<T, U, V>(this Tuple<T, U> t, V v) { return new Tuple<T, Tuple<U, V>> { First = t.First, Second = t.Second.Glue(v) }; }
This should do it in a recursive manner. Let see what is the out put: What? What happened at step 3? Sure the compiler recognized { Hi, 255 } as Tuple<string, byte>; but why the first version of Glue executed not the second one, overloaded for a Tuple<T, U>? Is this something about generics in C#? After all implementing tuples in a statically strongly typed manner without compiler support (internal or by a macro system) is pointless, I know. But from this pointless try I have touched another problem: In C# I can not have real accumulated types, but just parametrized types which does not provide enough tools for composition. Thanks in advance By kaveh.shahbazian at 2009-08-21 21:50 | LtU Forum | previous forum topic | next forum topic | other blogs | 6338 reads
|
Browse archives
Active forum topics |
Recent comments
23 weeks 1 day ago
23 weeks 1 day ago
23 weeks 1 day ago
45 weeks 2 days ago
49 weeks 4 days ago
51 weeks 1 day ago
51 weeks 1 day ago
1 year 1 week ago
1 year 6 weeks ago
1 year 6 weeks ago