Wednesday, March 5, 2008
C# Universal Type Converter
using System;
using System.Collections.Generic;
using System.Text;
namespace UniversalTypeConverter
{
class Program
{
static void Main(string[] args)
{
Obj obj = new Obj();
obj["Name"] = "Joe";
obj["Age"] = 27;
obj["StartDate"] = new DateTime(2002, 9, 8);
Write(obj);
obj["Name"] = "Mike";
obj["Age"] = 34;
obj["StartDate"] = new DateTime(2005, 12, 5);
Write(obj);
Console.ReadLine();
}
static void Write(Obj obj)
{
string name = obj["Name"];
int age = obj["Age"];
DateTime startDate = obj["StartDate"];
Console.WriteLine("name={0} age={1} start={2:d}",
name, age, startDate);
}
}
public class Obj
{
Dictionary m_PropValues = new Dictionary();
public PropValue this[string name]
{
get
{
PropValue prop = null;
m_PropValues.TryGetValue(name, out prop);
return prop;
}
set
{
if (m_PropValues.ContainsKey(name))
{
m_PropValues[name] = value;
}
else
{
PropValue prop = value;
m_PropValues.Add(name, prop);
}
}
}
}
public class PropValue
{
private object m_Value;
public object Value
{
get
{
return m_Value;
}
}
public PropValue(object val)
{
m_Value = val;
}
public static implicit operator PropValue(int val)
{
return new PropValue(val);
}
public static implicit operator PropValue(string val)
{
return new PropValue(val);
}
public static implicit operator PropValue(DateTime val)
{
return new PropValue(val);
}
public static implicit operator int(PropValue prop)
{
return (prop.Value as int?) ?? -1;
}
public static implicit operator string(PropValue prop)
{
return (prop.Value as string) ?? string.Empty;
}
public static implicit operator DateTime(PropValue prop)
{
return (prop.Value as DateTime?) ?? DateTime.MinValue;
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment