Skip to main content
 首页 » 编程设计

c#之Linq to SQL 扩展方法 : Method overloading, 错误

2024年02月13日10qlqwjy

如果答案很明显,我深表歉意,但谷歌没有找到答案(可能是因为我可能没有使用理想的措辞)。我正在尝试为具有多个类的用户重载我创建的 LINQ 方法签名;每个签名都需要自己的逻辑。我有以下内容:

public static class myExtension // TODO: Rename. 
{ 
    public static IQueryable<TypeA> IsReadableBy<T>(this IQueryable<TypeA> query, User user) 
        where T : TypeA 
    { 
        if (user.foo("argument")) { 
            return query; 
        } else if (!user.bar("argument2")) { 
            return query.Where(q => q.Collection1.Count == 0 && q.Collection2.Count == 0); 
        } else { 
            return query.Where(q => q.Collection1.Any(x => x.User.Id == user.Id) 
                || q.Collection2.Any(x => x.Group.HasUser(user))); 
        } 
    } 
} 

现在,当我尝试将以下内容添加到 MyExtension 类时,它失败了:

public static IQueryable<TypeB> IsReadableBy<T>(this IQueryable<TypeB> query, User user) 
    where T : TypeB 
{ 
    if (user.foo("argument") || user.bar("argument2")) 
    { 
        return query; 
    } 
    else  
    { 
        return query.Where(q => q.Collection1.Any(x => x.User.Id == user.Id) 
            || q.Collection2.Any(x => x.Group.Users.Any(u => u.User.Id == user.Id))); 
    } 
} 

这破坏了一切,即使方法签名应该不同。我尝试将新方法添加到它自己的类中,但没有成功。如何重载这样的方法?

编辑:我得到的错误是 -

'System.Linq.IQueryable' does not contain a definition for 'IsReadableBy' and no extension method 'IsReadableBy' accepting a first argument of type 'System.Linq.IQueryable' could be found (are you missing a using directive or an assembly reference?)

The type arguments for method 'Extensions.ModelExtensions.IsReadableBy(System.Linq.IQueryable, Data.Entities.User)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

请您参考如下方法:

如果您已经知道类型,为什么还需要泛型方法?只需使用以下方法签名,它应该适合您。

public static IQueryable<TypeB> IsReadable(this IQueryable<TypeB> query, User user)