Feedback

Generic Type Creator

Sprache: C#

Angenommen es wird zu weiteren Verarbeitung ein Dictionary vom Typ Dictionary<Guid, T> benötigt. Damit der Aufruf allerdings komfortabler ist soll es die möglichkeit geben die Daten in Form einer IList<T> an die Methode zu übergeben, dann kann folgendes Snippet helfen
// aufruf
        public void testRun()
        {
            IList<int> var = new List<int>();
            TestMethod(var);
        }
        public void TestMethod(object var)
        {
            if (var.GetType().IsGenericType)
            {
                Type[] t = var.GetType().GetGenericArguments();
                Type typeToGenerate = typeof(Dictionary<,>);
                Type[] tParameters = new Type[] { typeof(Guid), t[0] };
                Type newType = typeToGenerate.MakeGenericType(tParameters);
                object obj = Activator.CreateInstance(newType);
            }
            else
            {
                throw new InvalidCastException("Wrong type");
            }
            // do something with the new Dictionary...
        }
// aufruf
        public void testRun()
        {
            IList<int> var = new List<int>();
            TestMethod(var);
        }
        public void TestMethod(object var)
        {
            if (var.GetType().IsGenericType)
            {
                Type[] t = var.GetType().GetGenericArguments();
                Type typeToGenerate = typeof(Dictionary<,>);
                Type[] tParameters = new Type[] { typeof(Guid), t[0] };
                Type newType = typeToGenerate.MakeGenericType(tParameters);
                object obj = Activator.CreateInstance(newType);
            }
            else
            {
                throw new InvalidCastException("Wrong type");
            }
            // do something with the new Dictionary...
        }

3 Kommentare

  1. IList kann man schonmal nicht nach IListcasten, von daher geht der Aufruf aus testRun() nicht –> TestMethod(object var) muss es heissen.

    [code]
    public static void Test(IList list)
    {
    Dictionary dict = new Dictionary();
    }
    [/code]