如何调用扩展 IDictionary 的方法(反射)?
我已经像这样扩展了 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>;
它说它无法转换为非委托类型。
正确的调用方式是什么?
/Lasse
- UPDATE *
将代码更改为:
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您缺少末尾的括号:
编译器认为您想要将方法(委托)分配给变量。
另外,您可以使用
typeof(T)
而不是someObject.GetType()
,我会在循环外部创建一个变量并重用它。You're missing the brackets on the end:
The compiler thought you wanted to assign the method (delegate) to the variable.
Also, instead of
someObject.GetType()
you could usetypeof(T)
, I'd create a variable outside the loop and reuse it too.