Skip the general list in the ObservableCollection constructor

I'm sure something is missing here, but some special reason for this is not working?

public ObservableCollection<object> ItemCollection { get; set; } private void SetListData<T>(List<T> MyList) { ItemCollection = new ObservableCollection<object>(MyList); } 

Is there any value for T where this will not work? I believe that a collection of objects will cover every case, but this is not the case:

Error 2 Argument 1: Cannot convert from 'System.Collections.Generic.List <T> ' to 'System.Collections.Generic.List <object>

Changing the property signature will cause a whole new set of problems, so change it to:

 ItemCollection = new ObservableCollection<T>(MyList); 

doesn't seem like a good solution. Can someone tell me why my source code is not working and if there is some easy fix?

+4
source share
3 answers

You have several options:

 private void SetListData<T>(List<T> MyList) where T : class 

or

 ItemCollection = new ObservableCollection<object>(MyList.Cast<object>()); 

If you have a List<T> known reference type, it can work, although the type parameter is not an object :

 var list = new List<string>(); var observable = new ObservableCollection<object>(list); 

But in this case, you are using a generic parameter that is not a known reference type; it may be the type / structure of the value. They can be “boxed” as object , but are not essentially object s.

Thus, you must either restrict this parameter to always be a reference type, or allow any type T , and make an explicit cast to object inside the body of the method.

+5
source

The problem is that "T" is not an "object", although "T" inherits an "object". The types in shared lists must be the same.

Your best solution would be:

 ItemCollection = new ObservableCollection<object>(); foreach(T item in MyList) { ItemCollection.Add(item); } 
+1
source

You are almost there. List<T> converted to IEnumerable<object> (due to covariance) only when T is a reference type. Thus, limiting T as a reference type will work:

 private void SetListData<T>(List<T> MyList) where T : class { ItemCollection = new ObservableCollection<object>(MyList); } 
+1
source

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


All Articles