今天开始了将控制台应用程序迁移到VS2022和C#10的新任务,并遇到了一个无法找到解决办法的显示停止器,除了使用编译器指令来抑制警告之外。我希望避免这种情况,因为这个应用程序有成百上千个使用类似语法的LINQ查询。下面是我遇到的一些基本知识。
public static class ResponseCodes
{
public static string MEI0066 => "ME-I0066";
public static string MEI0069 => "ME-I0069";
public static string MEI0070 => "ME-I0070";
}
public class DebugLog
{
public DebugLog()
{
this.DebugLogId = null;
this.LogType = string.Empty;
this.ResponseCode = string.Empty;
this.Explanation = string.Empty;
}
public DebugLog(int? p_id, string p_logType, string p_responseCode, string p_explaination)
{
this.DebugLogId = p_id;
this.LogType = p_logType;
this.ResponseCode = p_responseCode;
this.Explanation = p_explaination;
}
public int? LogId { get; set; }
public string ResponseCode { get; set; }
public string Explanation { get; set; }
public string LogType { get; set; }
}
public enum LogEntryTypes
{
BlackListedIP,
DNSQuerySuccess,
DNSQueryFailed,
WhiteListedIP
}
public class QueryLogs
{
public QueryLogs()
{
this.DebugLogQueue = new List<DebugLog>();
}
public List<DebugLog> DebugLogQueue {get;set;}
public DebugLog? Query()
{
DebugLog _debugLog = new DebugLog()
{
LogId = 0,
LogType = LogEntryTypes.DNSQuerySuccess.ToString(),
Explanation = "IP was valid",
ResponseCode = ResponseCodes.MEI0070
};
DebugLogQueue.Add(_debugLog);
_debugLog = new DebugLog(1, LogEntryTypes.BlackListedIP.ToString(), "This a test", ResponseCodes.MEI0066);
DebugLogQueue.Add(_debugLog);
_debugLog = new DebugLog(2, LogEntryTypes.DNSQueryFailed.ToString(), "This string is not null", ResponseCodes.MEI0069);
DebugLogQueue.Add(_debugLog);
// This LINQ query gives a CS8600 warning "Converting null literal or possible
// null value to non-nullable type.
DebugLog returnValue = DebugLogQueue
.FirstOrDefault(x =>
(x.ResponseCode == ResponseCodes.MEI0069)
&& (x.LogType == LogEntryTypes.DNSQueryFailed.ToString()));
// This form uses the null-coalescing operator but gives CS1662 warning
// "Cannot convert lambda expression to intended delegate type because some of
// the return types in the block are not implicitly convertible to to the
// delegate return type."
returnValue = DebugLogQueue
.FirstOrDefault(x => (x.ResponseCode ?? ResponseCodes.MEI0069));
return returnValue;
}
}曾经尝试过的:
因为类ResponseCodes是静态的,所以它的值永远不会为空。
由于枚举LogEntryTypes在使用时被转换为字符串,因此它们将永远不会返回空值。
正如其他帖子所建议的,我尝试了以下几点:
因此,在发出和返回属性值时,CS8600和CS1662警告必须来自LINQ一方,但在我的生命中,我还没有想出正确的语法来编写查询,从而消除警告。我甚至不知道在这个问题上该往哪里看。
那么,我是在这里遗漏了什么,还是说这是C#10中LINQ查询的一种无效方法?
发布于 2022-02-07 22:49:46
在使用net6时,大多数问题都是由c#这种愚蠢的可空特性引起的。最糟糕的是,它在默认情况下进入新项目,大多数人花费大量时间试图找出为什么它会突然停止工作或发出奇怪的警告。只需在你的网络中创建这个小的主题文件。
<TargetFramework>net6.0</TargetFramework>
<!--<Nullable>enable</Nullable>-->https://stackoverflow.com/questions/71025034
复制相似问题