[英]how can i loop through dynamic ObservableCollection class inside method
hi, I'm trying to pass dynamic [ ObservableCollection ] List to method how can i get keys and loop through values from inside method without passing the Class [ Player ]嗨,我正在尝试将动态 [ ObservableCollection ] 列表传递给方法如何在不传递 Class [ Player ] 的情况下从方法内部获取键并循环遍历值
this my code这是我的代码
{
public static ObservableCollection<Player> items = new ObservableCollection<Player>();
public TEST()
{
InitializeComponent();
GroupsDataG.ItemsSource = items;
}
public class Player
{
public int ID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Add Random Data On Click
items.Add(new Player() { ID = 1, FName = "aaaa", LName = "bbbb" });
items.Add(new Player() { ID = 2, FName = "cccc", LName = "yyyyy" });
// Passing The [ObservableCollection] List to a method
GetMyData(items);
}
public static void GetMyData<T>(ObservableCollection<T> collection)
{
// How Can i get values
foreach (var item in collection)
{
//
}
}
}
Create an interface that has common properties/methods you wish to access "generically" and then use that in your GetMyData method.创建一个具有您希望“一般”访问的通用属性/方法的接口,然后在您的 GetMyData 方法中使用它。 GetMyData may then access anything defined in this interface regardless of what class T is as long as it implements the interface: GetMyData 然后可以访问此接口中定义的任何内容,而不管 class T 是什么,只要它实现了该接口:
public interface IPlayer
{
int ID { get; }
string FName { get; set; }
string LName { get; set; }
}
public class Player : IPlayer
{
public int ID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
}
public class SomeOtherPlayer : IPlayer
{
public int ID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public int Score { get; set; }
}
//you can also change the parameter from ObservableCollection to IEnumerable if all you need is to iterate through a collection. this allows the method to accept different types of generic collections and not just ObservableCollection.
public static void GetMyData<T>(IEnumerable<T> collection) where T : IPlayer
{
// How Can i get values
foreach (T player in collection)
{
//now you can access IPlayer
player.ID = 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.