New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Generic

13 Views
Copy Code Show/Hide Line Numbers
static void Main(string[] args)
{
    Dictionary<string, string> dStr = new Dictionary<string,string>();
    dStr["Hello"] = "World";
    SomeGenericFunc<string>(dStr);
 
    Dictionary<string, int> dInt = new Dictionary<string, int>();
    dInt["Age"] = 10;
    SomeGenericFunc<int>(dInt);
 
    Console.Read();
}
 
private static void SomeGenericFunc<T>(Dictionary<string, T> dict)
{
    foreach (KeyValuePair<string, T> pair in dict)
    {
        // Funkar ju men inte tillräckligt generiskt...
        T t = pair.Value;
        if (typeof(T) == typeof(string))
        {
            SomeFunc((string)(object)t);
        }
        else if (typeof(T) == typeof(int))
        {
            SomeFunc((int)(object)t);
        }
 
        // Vill kunna anropa rätt överlagrad metod direkt:
        SomeFunc(t); // Fungerar ej..
    }
}
private static void SomeFunc(int nVal)
{
    Console.WriteLine(nVal);
}
 
private static void SomeFunc(string strVal)
{
    Console.WriteLine(strVal);
}
 
by
  February 08, 2010 @ 12:46pm

Add a comment


Report Abuse
brought to you by:
West Wind Techologies


If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate