Can you solve this?

by rsutton 22. January 2010 07:27

There is an interesting problem I solved today that I thought I might share.  The basic idea can be solved by figuring out how to solve the following problem.


Consider this JavaScript
funcs = []
for(var i=0;i<10;i++)
       funcs[i] = function() { alert(i); }
funcs[4]();

This will alert "10".  Can you change it to alert "4"?  The key to solving this problem is being able to create a function that stores i and then will evaluate the alert later.

Also
funcs[0] alerts "0"
funcs[1] alerts "1"
...
funcs[9] alerts "9"

Get the idea?  Good luck!

Tags:

Development

Get Values Out of a Dictionary Using Reflection in C#

by rsutton 6. January 2010 04:41

As part of the project I’m currently working on I had the need to get all the values out of a dictionary without the benefit of typing, so I had to use reflection.  Here is the best was I’ve been able to come up with and hopefully it is useful to others.

    1 

    2 private void GetDictionaryValues(object obj)

    3 {

    4     var t = obj.GetType();

    5 

    6     // Handle dictionaries.

    7     if (typeof(IDictionary).IsAssignableFrom(t))

    8     {

    9         // Get the methods we need to deal with dictionaries.

   10         var keys = t.GetProperty("Keys").GetGetMethod().Invoke(obj, null);

   11         var item = t.GetProperty("Item");

   12         var enumerator = keys.GetType().GetMethod("GetEnumerator").Invoke(keys, null);

   13         var moveNext = enumerator.GetType().GetMethod("MoveNext");

   14         var current = enumerator.GetType().GetProperty("Current").GetGetMethod();

   15 

   16         // Get all the values.

   17         while ((bool)moveNext.Invoke(enumerator, null))

   18         {

   19             var key = current.Invoke(enumerator, null);

   20             var value = item.GetValue(obj, new object[] { key });

   21 

   22             // Do Stuff.

   23         }

   24     }

   25 }

   26 

Tags:

Development

Powered by BlogEngine.NET 1.4.5.0
Theme by Extensive SEO

Profile

Member of the Church of Jesus Christ of Latter-Day Saints, Developer and IT Professional