试图在我的代码中找到错误的来源

编程入门 行业动态 更新时间:2024-10-23 15:33:52
本文介绍了试图在我的代码中找到错误的来源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary3 { public class Destination { public string DestinationName; // Nom de l'opérateur public List<int> PrefixCall; // Les codes de l'opérateurs +216 9 216 7 public int MinDigit; // Nombre minimum des chiffres public int MaxDigit; public string DestinationType; // Termination, VAS, MSRN Roaming public List<Trunk> Trunks; public bool ExistPrefixCall(int code) { if (PrefixCall.Exists(code))//i have problem here return true; return false; } public bool addPrefixCall(int code) { if (PrefixCall.Exists(code))//i have problem here return false; else { PrefixCall.Add(code); return true; } } } }

我尝试过: 前缀是一个整数列表我不知道为什么当我使用exists属性时它会给出错误

What I have tried: prefixcall is a list of integer i don't know why it gives error when i use exists property

推荐答案

你的列表需要初始化;例如 Your "list" needs to be "initialized"; e.g. public List<int> PrefixCall = new List<int>(); // Les codes de l'opérateurs +216 9 216 7

...否则只会是空。

... otherwise it will just be "null".

当您定义自己的谓词以检查元素是否存在时,使用Exists方法。因此,该方法希望您提供一个谓词,而不仅仅是一个数字。 根据您发布的代码,您似乎只想知道一个数字是否是在列表中与否。为此,请尝试使用列表< t> .Contains(T)方法 [ ^ ] Exists method is used when you define your own predicate to check whether an element exists or not. So the method expects you to provide a predicate, not just a number. Based on the code you posted it looks like you just want to find out if a number is in the list or not. For this purpose try to use List<t>.Contains(T) Method [^]

在Gerry Schmitz的解决方案上稍微扩展一下: 您需要做的是测试'PrefixCall为null,和/或测试'PrefixCall没有条目。 我喜欢利用可空的布尔来处理这样的任务: To expand a little on the solution by Gerry Schmitz: What you need to do is test 'PrefixCall for null, and/or test 'PrefixCall for having no entries. I like to handle tasks like this by taking advantage of a nullable bool: public bool? ValidatePrefixCall() { if(PreFixCall == null) return null; return PreFixCall.Count > 0; } public bool ThrowOnNullList = true; // use example bool? pfcIsValid = ValidatePrefixCall(); if (pfcIsValid == true) { // the list is initialized and has at least one item } else { if (pfcIsValid == false) { // the list is initialized and has no items } else { // the list is not initialized if (ThrowOnNullList) { throw new NullReferenceException("PreFixCall is null"); } } }

更多推荐

试图在我的代码中找到错误的来源

本文发布于:2023-11-08 16:04:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   来源   代码   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!