After almost 20 years using Visual FoxPro, I’m suffering with strong type language. :).
I’m trying to create a generic method, using one interface, to set a DataGrid.ItemsSource property.
Here we go…
First, I have a class (POCO):
public class PersonVO
{
public int PersonID { get; set; }
public string Name { get; set; }
}
Then I created an interface:
public interface IBussiness
{
List<T> GetAll<T>();
}
And then, other class that implements this interface…
public class PersonBLL : IBussiness
{
public List<PersonVO> CreateNewList()
{
List<PersonVO> list = new List<PersonVO>();
list.Add(new PersonVO() { PersonID = 1, Name = "Robert" });
list.Add(new PersonVO() { PersonID = 2, Name = "Julie" });
list.Add(new PersonVO() { PersonID = 3, Name = "Bernard" });
return list;
}
public List<T> GetAll<T>()
{
return CreateNewList();
}
}
The statement return CreateNewList() shows an error:
C#: An instance of type
‘System.Collections.Generic.List’ can
not be returned by a method of type ‘System.Collections.Generic.List’
So I changed this method to:
public List<T> GetAll<T>()
{
return CreateNewList() as List<T>;
}
It compiles!
Now, my problem starts… I have a WPF usercontrol MyTabItemList.
My point is, I create a new WPF TabItem at runtime, and inject my BLL class (in this example PersonBLL, but in real world I have a lot of them…).
MyTabItemList myTabItem = new MyTabItemList(new PersonBLL());
MyTabItemList is something like this:
public partial class MyTabItemList : TabItem
{
IBussiness oBLL;
public MyTabItemList(IBussiness oBLL)
{
InitializeComponent();
this.oBLL = oBLL;
MyGrid.ItemsSource = oBLL.GetAll<object>();
}
}
It runs ok, but doesn’t work like I would like it to.
oBLL.GetAll<object>() always returns null.
If I change <object> to <PersonBLL> (like below), it works, but in this case MyTabItemList just works with PersonBLL class:
MyGrid.ItemsSource = oBLL.GetAll<PersonBLL>();
What should I do to make it work?
Why do you want to return a generic list from a none generic component like this?
I think your purpose is:
and make your
PersonBLLimplementIBussiness<PersonVO>:That’s one of the normal patterns.