开发者

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:

  1. The obvious type-safe code.
  2. Casting as necessary, followed by type-safe code.
  3. Generating a delegate by constructing and compiling an expression-tree.
  4. The use of dynamic.
  5. AutoMapper and other libraries.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜