C# 中的 Func 泛型型別


Func 泛型型別儲存匿名方法,並且是引數化型別。

在下面的示例中,我們有 4 個 func 型別例項 −

第一個型別接收 int 並返回 string

Func<int, string> one = (p) => string.Format("{0}", p);

第二個型別接收 bool 和 long 並返回 string

Func<bool, long, string> two = (q, p) =>string.Format("{0} and {1}", q, p);

第三個型別接收 bool 和 int 並返回 string

Func<bool, int, string> three = (q, p) => string.Format("{0} and {1}", q, p);

第四個型別接收 decimal 並返回 string

Func<decimal, string> four = (p) =>string.Format("{0}", p);

讓我們看看如何顯示它們 −

示例

 動態演示

using System;
using System.IO;

namespace Demo {
   class Program {
      static void Main(string[] args) {

         // four func type instance
         // first type receives int and returns string
         Func<int, string> one = (p) =>
         string.Format("{0}", p);

         // second type receives bool & long and returns string
         Func<bool, long, string> two = (q, p) =>
         string.Format("{0} and {1}", q, p);

         // three type receives bool & int and returns string
         Func<bool, int, string> three = (q, p) =>
         string.Format("{0} and {1}", q, p);

         // fourth type receives decimal and returns string
         Func<decimal, string> four = (p) =>
         string.Format("{0}", p);

         Console.WriteLine(one.Invoke(25));
         Console.WriteLine(two.Invoke(false, 76756566));
         Console.WriteLine(three.Invoke(true, 50));
         Console.WriteLine(four.Invoke(1.2m));
      }
   }
}

輸出

25
False and 76756566
True and 50
1.2

更新於:22-Jun-2020

773 次瀏覽

開啟你的 職業生涯

透過完成教程來獲取認證

開始使用
廣告
© . All rights reserved.