I do some asp.net programming work. Usually, I get parameters from Request.QueryString or Request.Form. Both of them return values of string.
We usually need both string and int types of one parameter, int type for computing, string type for Response.Writing to the client. So there are so many type
converting int my code.....
So I want to make a generic class that contains many types of on value.
public class Converter<T>
{
private T original;
//for caching, box/unbox for value types ,but I cannot find better method.
private Dictionary<Type, Object> cache = new Dictionary<Type, Object>();
public Converter(T value)
{
this.cache.Clear();
this.original = value;
}
public T Original
{
get { return this.original ; }
set
{
this.cache.Clear();
this.original = value;
}
}
public U ToType<U>()
{
if(typeof(U) == typeof(T))
return this.original;
if(!this.cache.Keys.Contains(typeof(U)))
{
//Convert this.original to the type of U value;
U tmp = xxxxxxxxxxxxxxxxxxx; //how to write code here????
this.cache.Add(typeof(U), tmp);
}
return (U)this.cache[typeof(U)];
}
}
So :
bindTable(int page, int pageSize) { ... }
...
Converter ctr = new Converter<string>(Request.QuerySting["page"]);
Response.Write("this is the " + cter.Original + " page.");
bindTable(ctr.ToType<int>(), pageSize)...
Extend this class, not only the primitive types like int, bool, string, datetime, but also custom classes can be supported, like :
public class class1 { ... }
public class class2
{
...
public static explicit/implicit operator class1(class2) { ... }
...
}
public class class3 : class2 { ... }
...
Converter cter = new Converter<class2>(new class2());
class1 inst1 = cter.ToType<class1>();
cter.Original = new Class3();
class1 inst11 = cter.ToType<class1>();
The problem is I cannot write the code that convert value of type T to value of type U in the above code......
.NET hidden so many details, and Microsoft has so many encapsulation experts. I think they forget the very important idea of programming : keep simple...