About the component Model and reflection

I have a function that takes any object, then it gets the values ​​from the properties or fields that it has as input.

Now it looks like this:

private string GetFieldValue(object o, Field f) { //field.name is name of property or field MemberInfo[] mi = o.GetType().GetMember(field.name, MemberTypes.Field | MemberTypes.Property, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.ExactBinding ); if (mi.Length == 0) throw new ArgumentException("Field", "Can't find member: " + f.name); Object value; if (mi[0].MemberType == MemberTypes.Property) value = ((PropertyInfo)mi[0]).GetValue(o, null); else value = ((FieldInfo)mi[0]).GetValue(o); 

Today I read about System.ComponentModel and its XXXDescriptor classes. What is the difference, when it comes to performance, between two frames (Reflection and ComponentModel). Does this overwrite using ComponentModel provide better performance or flexibility? The only difference between the two that I know is support for virtual properties using CM.

Ty.

+4
source share
2 answers

The difference is that the ComponentModel is an abstraction of the raw classes. This means that you can define properties that do not exist , and indeed, that is how DataView / DataRowView expands columns as data binding properties. Using ComponentModel, you can get something like "dynamic" even in version 1.1.

You might think that ComponentModel is slower; but actually you can use this abstraction to enhance ... HyperDescriptor does just that - using Reflection.Emit to write direct IL to represent properties, providing much faster access than the reflection or vanilla component of the ComponentModel.

Note, however, that the ComponentModel is by default limited to properties (not fields). You can do this with PropertyDescriptor torches on the fly, but this is not a good idea. There is also not much room for the "write only" property in the ComponentModel.

+6
source

TypeDescriptor (in System.ComponentModel ) caches internally, so it may have better performance, although nothing prevents you from adding a cache to the above code. TypeDescriptor uses reflection, although it allows you to expand your object and add properties and events that are not supported by "real" properties and events. TypeDescriptor does not support fields.

If I were you and I didn’t like the extensibility functions of TypeDescriptor , and I was happy to add my own cache on top of GetMember , then I would stick to the reflection.

Edit: Standard reflection has cached MemberInfo objects with 2.0 - see the MSDN "Using .NET: Avoid the General Performance of Pitfalls for Speedier Applications" .

+3
source

All Articles