C# params可變參數(shù)的使用注意詳析
今天在一個(gè) .NET Core 項(xiàng)目中調(diào)用一個(gè)自己實(shí)現(xiàn)的使用 params 可變參數(shù)的方法時(shí)觸發(fā)了 null 引用異常,原以為是方法中沒(méi)有對(duì)參數(shù)進(jìn)行 null 值檢查引起的,于是加上 check null 代碼:
public static void BuildBlogPostLinks(params BlogPostDto[] blogPosts)
{
if (blogPosts == null)
return;
foreach (var blogPost in blogPosts)
{
//...
}
}
結(jié)果卻出人意料, null 引用異常繼續(xù),仔細(xì)看異常 stack 才發(fā)現(xiàn)原來(lái) null 引用異常是在 foreach 時(shí)拋出的,需要在 foreach 時(shí)對(duì) blogPost 進(jìn)行 check null 。
下面的示例代碼可以驗(yàn)證這一點(diǎn)
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; }
}
運(yùn)行時(shí)的輸出結(jié)果是
$ dotnet run
blogPosts in null
blogPost in null
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
- c# 可變數(shù)目參數(shù)params實(shí)例
- C#中Params的用法
- C#難點(diǎn)逐個(gè)擊破(3):params數(shù)組參數(shù)
- C# 運(yùn)用params修飾符來(lái)實(shí)現(xiàn)變長(zhǎng)參數(shù)傳遞的方法
- asp.net(c#)ref,out ,params的區(qū)別
- 用C#中的params關(guān)鍵字實(shí)現(xiàn)方法形參個(gè)數(shù)可變
- 用C#的params關(guān)鍵字實(shí)現(xiàn)方法形參個(gè)數(shù)可變示例
- c#的params參數(shù)使用示例
- 詳解C#中三個(gè)關(guān)鍵字params,Ref,out
相關(guān)文章
C#算法函數(shù):獲取一個(gè)字符串中的最大長(zhǎng)度的數(shù)字
這篇文章介紹了使用C#獲取一個(gè)字符串中最大長(zhǎng)度的數(shù)字的實(shí)例代碼,有需要的朋友可以參考一下。2016-06-06
WPF實(shí)現(xiàn)上下滾動(dòng)字幕效果
這篇文章主要為大家詳細(xì)介紹了WPF實(shí)現(xiàn)上下滾動(dòng)字幕效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
基于C#實(shí)現(xiàn)自定義計(jì)算的Excel數(shù)據(jù)透視表
數(shù)據(jù)透視表(Pivot?Table)是一種數(shù)據(jù)分析工具,通常用于對(duì)大量數(shù)據(jù)進(jìn)行匯總、分析和展示,本文主要介紹了C#實(shí)現(xiàn)自定義計(jì)算的Excel數(shù)據(jù)透視表的相關(guān)知識(shí),感興趣的可以了解下2023-12-12
C#對(duì)XML文件的各種操作實(shí)現(xiàn)方法
C#對(duì)XML文件的各種操作實(shí)現(xiàn)方法,需要的朋友可以參考一下2013-04-04
c#中使用BackgroundWorker的實(shí)現(xiàn)
本文主要介紹了c#中使用BackgroundWorker的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06

