Setting a field on an object that is a property in a class using reflection in .NET
I have the following class structure (pseudocode):
Class A
{
Property string Who;
Property string Where;
}
Class B
{
Property A Information;
}
Class C
{
Property String Who;
}
I am trying to find out how to set se开发者_JAVA百科t B.A.Who = C.Who
using reflection in .NET 4.0.
Thanks!
Well, this isn't all that difficult to do sort of correctly, but it would get really messy if you wanted argument-validation, graceful error-handling etc. Here's an example that should highlight the technique (no checks):
static void SetBsAsWhoToCsWho(object b, object c)
{
// csWho = c.Who
object csWho = c.GetType().GetProperty("Who").GetValue(c, null);
// a = b.Information
object a = b.GetType().GetProperty("Information").GetValue(b, null);
// a.Who = csWho
a.GetType().GetProperty("Who").SetValue(a, csWho, null);
}
You need all sorts of checks in the above code to make it robust. It would really help if you could tell us why you want to use reflection to accomplish this task. Depending on the scenario, there may be solutions that are more appropriate, such as:
- The obvious type-safe code.
- Casting as necessary, followed by type-safe code.
- Generating a delegate by constructing and compiling an expression-tree.
- The use of
dynamic
. - AutoMapper and other libraries.
精彩评论