不能在Indexer Get方法中使用LINQ查询

时间:2019-05-24 13:57:27

标签: c#

C#中的索引器是否有任何限制?

不能在get方法中使用LINQ:

'User' does not contain a definition for 
'Id' and no accessible extension method 'Id' accepting a 
first argument of type 'User' could be found
(are you missing a using directive or an assembly reference?)

很奇怪,因为在此存储库之外,我可以使用LINQ。喜欢 User user = users.First(x => x.Id == id);

public class User
{
    public int Id { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
    public string Name { get; set; }
    public Uri Avatar { get; set; }
}

public class MockRepository<User>
{
    private List<User> _users = new List<User>() { ... };

    public User this[int index]
    {
        get { return _users.First(x => x.Id == index); }
                                       ^^^^
    }
}

1 个答案:

答案 0 :(得分:3)

您引用的是通用类型User,而不是类User。如果需要使用User属性,还需要Type Contraint

public class MockRepository<TUser> where TUser : User
{
    private List<TUser> _users = new List<TUser>() { ... };

    public User this[int index]
    {
        get { return _users.First(x => x.Id == index); }
    }
}

这就是为什么我们总是在Type参数上使用前缀T;)