我想在集合上创建自定义索引器。这是我的类(class):
商务舱:
public class UserCollection : Collection<User>
{
public new User this[int index]
{
get
{
return this.FirstOrDefault(x => x.UserID == index);
}
}
}
BL API 方法:
public static Collection<User> GetUser()
{
return new UserCollection
{
new User {UserID = 2},
new User {UserID = 4}
};
}
用法:
Collection<User> users = GetUser();
User user = users[2];
}
用户类有几个列,如 UserID、UserName 等。我想通过索引从集合中获取用户,这里的索引将是用户 ID。但是上面的使用代码并没有这样做,它是在考虑父Collection类的索引器。我想让我的自定义索引器发挥作用。我可以通过将 UserCollection 公开为 GetUser 方法的返回类型来实现,然后解决方案是使用这样的代码
UserCollection users = GetUser();
但我正在考虑从这里的 BL 方法返回最通用的类型,即 Collection。我该如何解决这个问题?
最佳答案
阅读 Collection<T>
的文档仔细关注“继承者须知”部分。它将链接到另一个页面,该页面为您提供了执行您正在尝试执行的操作的示例。
您可能还想查看 KeyedCollection<TKey, TItem>
类,这可能会让你的事情变得更容易一些。您的自定义类将简单地变为:
public class UserCollection: KeyedCollection<int, User>
{
public UserCollection() : base() {}
protected override int GetKeyForItem(User user)
{
return user.UserID;
}
}
关于c# - 在集合上实现自定义索引器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9948722/