简体   繁体   中英

C# get the types defining a Dictionary at run time

I was wondering what is the best way for getting the generic arguments that definine a dictionary at run time is.

Take for example:

Dictionary<string, object> dict;

How at runtime can I find out that the keys are strings?

I'm not sure if I understand your question correctly but I think you mean something like this:

Dictionary<string, object> dict = new Dictionary<string, object>();
// ...
var args = dict.GetType().GetGenericArguments();
// args[0] will be typeof(string)

Here's an NUnit test to demonstrate Mehrdad's answer, and with a dictionary containing integers as keys, and strings as values:

        [Test]
        public void testGetPhysicalTypeForGenericDictionary()
        {
            IDictionary<int, string> myDictionary = new Dictionary<int, string>();
            Type [] myTypes = myDictionary.GetType().GetGenericArguments();
            Assert.AreEqual(2, myTypes.Length);
            var varTypes = myDictionary.GetType().GetGenericArguments();
            Assert.AreEqual("Int32", varTypes[0].Name);
            Assert.AreEqual("System.Int32", varTypes[0].FullName);

            Assert.AreEqual("String", varTypes[1].Name);
            Assert.AreEqual("System.String", varTypes[1].FullName);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM