简体   繁体   English

在 lambda 表达式中使用私有方法

[英]Using private method in lambda expression

I am working on the logic handle and got this trouble.我正在处理逻辑句柄并遇到了这个麻烦。 If I use this code, it's not working:如果我使用此代码,则它不起作用:

private bool CheckDateTimeIsValid(DateTime startTime, DateTime endTime, DateTime dateTime)
{
    if (DateTime.Compare(startTime, dateTime) <= 0 && DateTime.Compare(endTime, dateTime) >= 0)
    {
        return true;
    }

    return false;
}

var listChallengeUsers = _context.ChallengeUseres
            .Where(cu => cu.AppUserId == activity.AppUserId)
            .Where(cu => cu.Challenge.ActivityType == activity.Type)
            .Where(cu => CheckDateTimeIsValid(cu.Challenge.StartTime, cu.Challenge.EndTime, activity.CreatedAt))

But if I use this, it worked:但是,如果我使用它,它会起作用:

var listChallengeUsers = _context.ChallengeUseres
            .Where(cu => cu.AppUserId == activity.AppUserId)
            .Where(cu => cu.Challenge.ActivityType == activity.Type)
            .Where(cu => DateTime.Compare(cu.Challenge.StartTime, activity.CreatedAt) <= 0 && DateTime.Compare(cu.Challenge.EndTime, activity.CreatedAt) >= 0 )
            .ToList();

Can someone help's me to know why it happen and how to use in the first way?有人可以帮助我了解它为什么会发生以及如何以第一种方式使用吗?

Your method isn't marked as "static", so either call it via instance or mark the method as static, like this:您的方法未标记为“静态”,因此要么通过实例调用它,要么将方法标记为 static,如下所示:

private static bool CheckDateTimeIsValid ( DateTime startTime, DateTime endTime, DateTime dateTime )
{
    if (DateTime.Compare ( startTime, dateTime ) <= 0 && DateTime.Compare ( endTime, dateTime ) >= 0)
    {
        return true;
    }

    return false;
}

Also, your code can be shorter like this:此外,您的代码可以像这样更短:

static bool CheckDateTimeIsValid ( DateTime startTime, DateTime endTime, DateTime dateTime ) => startTime <= dateTime && dateTime <= endTime;

And if u decide the method to be static, then it makes more sense to put this method as an extension, if u will use this method often in different places:如果你决定方法是 static,那么把这个方法作为一个扩展更有意义,如果你经常在不同的地方使用这个方法:

public static class DateTimeExts
{
    public static bool CheckDateTimeIsValid ( this DateTime dateTime, DateTime startTime, DateTime endTime ) => startTime <= dateTime && dateTime <= endTime;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM