2

我已经像这样扩展了 IDictionary:

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;
}

而且我在使用该方法时遇到问题,尝试如下:

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

它说它不能转换为非委托类型。

正确的称呼方式是什么?

/拉斯

  • 更新 *

将代码更改为:

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;
}
4

1 回答 1

5

你错过了最后的括号:

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

编译器认为您想将方法(委托)分配给变量。


此外,我会在循环外创建一个变量并重用它,而不是someObject.GetType()你可以使用。typeof(T)

于 2011-12-22T08:24:36.440 回答