C# params可變參數(shù)的使用注意詳析
今天在一個 .NET Core 項目中調用一個自己實現(xiàn)的使用 params 可變參數(shù)的方法時觸發(fā)了 null 引用異常,原以為是方法中沒有對參數(shù)進行 null 值檢查引起的,于是加上 check null 代碼:
public static void BuildBlogPostLinks(params BlogPostDto[] blogPosts)
{
if (blogPosts == null)
return;
foreach (var blogPost in blogPosts)
{
//...
}
}
結果卻出人意料, null 引用異常繼續(xù),仔細看異常 stack 才發(fā)現(xiàn)原來 null 引用異常是在 foreach 時拋出的,需要在 foreach 時對 blogPost 進行 check null 。
下面的示例代碼可以驗證這一點
class Program
{
static void Main(string[] args)
{
BuildBlogPostLinks(null);
BlogPost blogPost = null;
BuildBlogPostLinks(blogPost);
}
public static void BuildBlogPostLinks(params BlogPost[] blogPosts)
{
if (blogPosts == null)
{
Console.WriteLine("blogPosts in null");
return;
}
foreach (var blogPost in blogPosts)
{
if (blogPost == null)
{
Console.WriteLine("blogPost in null");
}
else
{
Console.WriteLine("blogpost.Title: " + blogPost.Title);
}
}
}
}
public class BlogPost
{
public string Title { get; set; }
}
運行時的輸出結果是
$ dotnet run
blogPosts in null
blogPost in null
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
相關文章
C#算法函數(shù):獲取一個字符串中的最大長度的數(shù)字
這篇文章介紹了使用C#獲取一個字符串中最大長度的數(shù)字的實例代碼,有需要的朋友可以參考一下。2016-06-06
基于C#實現(xiàn)自定義計算的Excel數(shù)據(jù)透視表
數(shù)據(jù)透視表(Pivot?Table)是一種數(shù)據(jù)分析工具,通常用于對大量數(shù)據(jù)進行匯總、分析和展示,本文主要介紹了C#實現(xiàn)自定義計算的Excel數(shù)據(jù)透視表的相關知識,感興趣的可以了解下2023-12-12
c#中使用BackgroundWorker的實現(xiàn)
本文主要介紹了c#中使用BackgroundWorker的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06

