Improving performance reflection - what alternatives should I consider?

前端 未结 6 1805
攒了一身酷
攒了一身酷 2020-12-01 05:29

I need to dynamically set values on a bunch or properties on an object, call it a transmission object.

There will be a fair number of these transmission objects that

6条回答
  •  眼角桃花
    2020-12-01 06:13

    In .NET 4.0 (beta), you can do this with the updated expression trees, using Expression.Block and Expression.Assign - then compile that to a typed delegate; job done.

    In .NET 2.0 and above (as Jon mentioned) HyperDescriptor is a reasonable option - it works as a custom PropertyDescriptor implementation, so you just do code like:

    // store this collection for optimum performance
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(
        typeof(SomeType));
    props["Name"].SetValue(obj, newName);
    props["DateOfBirth"].SetValue(obj, newDoB);
    

    This still has a little boxing, but that isn't actually a bottleneck.

提交回复
热议问题