Howto call method extending IDictionary (reflection)?
-
24-03-2021 - |
Вопрос
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.
Не связан с StackOverflow