I have extended IDictionary like this:

public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
     T someObject = new T();

     foreach (KeyValuePair<string, string> item in source)
     {
       someObject.GetType().GetProperty(item.Key).SetValue(someObject, item.Value, null);
     }

     return someObject;
}

And I'm having trouble using the method, tried it like this:

TestClass test = _rep.Test().ToClass<TestClass>;

And it says that it can't convert to non-delegate type.

What's the proper way of calling it?

/Lasse

  • UPDATE *

Changed code to:

public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
   Type type = typeof(T);
   T ret = new T();

   foreach (var keyValue in source)
   {
      type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value, null);
   }

   return ret;
}
有帮助吗?

解决方案

You're missing the brackets on the end:

TestClass test = _rep.Test().ToClass<TestClass>();

The compiler thought you wanted to assign the method (delegate) to the variable.


Also, instead of someObject.GetType() you could use typeof(T), I'd create a variable outside the loop and reuse it too.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top