Can I get the item type from a BindingSource?

I would like to get the type of the element to which the BindingSource is connected or configured. The BindingSource.DataSource property can be set as an object, list, or type. If it is a type, it clearly has no associated element, but I would still like to get a Type. For a list, I need a Type element, not a list type.

I currently have my own list type for business objects that implement the IListItemType interface, which I created to solve this problem some time ago. Now I would like to get this work in a more universal way so that it works with any list.

I looked at the API docs for a good way to do this, but so far I'm out of luck. Am I missing something or is it just something that I cannot or should not do?

+3
source share
3 answers

I recently walked in this context.

System.Windows.Forms.ListBindingHelper.GetListItemType () and GetListItemProperties ()

This class has everything I was looking for.

+6
source

"" . , , , ( , List<object>, string, , a List<string>). , ( , , ), .

, GetType . , , , IEnumerable<T>, , IEnumerable , . ( ) , .

TL, DR

. , .NET 3.5 , list:

var listType = list.GetType().GetInterfaces()
              .Where(t => t.Name == "IEnumerable" && t.IsGenericType)
              .Select(t => t.GetGenericArguments()[0]).FirstOrDefault();

IEnumerable<T>, T. , , - object.

+2

, , - ...

. , BindingSource.DataSource IEnumerable, . , BindingSource , "itemType". , : , BindingSource , BindingSource, .

, :

FieldInfo fi = 
    typeof(BindingSource)
    .GetField("itemType", BindingFlags.NonPublic | BindingFlags.Instance);
Type myElementType = fi.GetValue(DataBinder.RestrictedDataBinding) as Type;

, , innerList, , DataSource . , , , BindingSource ( IQueryables ..).

: , , , . , , DataSource BindingSource reset? , DataSource reset elementType? , .

Finally, using reflection to break into private fields breaks down all sorts of oop principles. Remember. Also, keep in mind that very well may be a good reason why the itemType field was hidden. If you need to further explore, the code for the BindingSource class is publicly available.

+1
source

Source: https://habr.com/ru/post/1749991/


All Articles