怪物奇妙物语

宇宙无敌超级美少男的怪物奇妙物语

首页 新随笔 联系 管理
  819 随笔 :: 0 文章 :: 2 评论 :: 16万 阅读

delegateActionFuncPredicate

在C#中,delegateActionFuncPredicate 都是用来处理方法引用或匿名方法的类型,但它们之间有一些关键的区别。

Delegate

delegate 是一个用户定义的类型,用于封装方法的引用。
它可以被实例化为特定的方法引用,并且可以被用来调用该方法。
delegate 类型需要显式地定义返回类型和参数列表。

代码示例:

demo

// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
// `delegate` 是一个用户定义的类型,用于封装方法的引用。
// `delegate` 类型需要显式地定义返回类型和参数列表。
public delegate int MyDelegate(int x, int y);
public class MyClass
{
public static int AddNumbers(int x, int y)
{
return x + y;
}
}
class Program
{
static void Main(string[] args)
{
// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
// 它可以被实例化为特定的方法引用,并且可以被用来调用该方法。
MyDelegate myDelegate = new MyDelegate(MyClass.AddNumbers);
int result = myDelegate(5, 3);
Console.WriteLine("Result: " + result);
}
}

发布器和订阅器

public delegate void NotificationHandler(string message);
public class EventPublisher
{
public event NotificationHandler OnNotification;
public void Notify(string message)
{
OnNotification?.Invoke(message);
}
}
public class EventSubscriber
{
public EventSubscriber(EventPublisher publisher)
{
publisher.OnNotification += HandleNotification;
}
private void HandleNotification(string message)
{
Console.WriteLine($"Received notification: {message}");
}
}
class Program
{
static void Main()
{
var publisher = new EventPublisher();
var subscriber = new EventSubscriber(publisher);
publisher.Notify("Hello, Delegate!");
}
}

Action

Action 是一个预定义的委托类型,它没有返回值。
Action 可以有零到十六个参数。
它是从 MulticastDelegate 继承来的,所以它支持事件。

代码示例:

demo1

// 箭头函数:👇👇👇👇👇👇👇👇👇👇
Action<string> printMessage = (message) => Console.WriteLine(message);
printMessage("Hello, World!");
// -------------------------------------------------------------------
static void SayHello(string name)
{
System.Console.WriteLine($"你好,{name}");
}
// 👇👇👇 👇👇👇
Action<string> printMessageTwo = SayHello;
printMessageTwo("Alice");
// -------------------------------------------------------------------
static void SayHelloToManyPeople(string name,string msg)
{
System.Console.WriteLine($"你好,{name},{msg}");
}
// 👇👇👇👇👇👇 👇👇👇👇👇👇👇👇
Action<string,string> printMessageThree = SayHelloToManyPeople;
printMessageThree("Alice","天气不错");

demo2

static void PerformTasks(Action task1, Action task2)
{
task1();
task2();
}
static void PrintHello()
{
Console.WriteLine("Hello");
}
static void PrintWorld()
{
Console.WriteLine("World");
}
PerformTasks(PrintHello, PrintWorld); // 输出 Hello World

Func

Func 是另一个预定义的委托类型,它可以有一个或多个输入参数,并且总是有一个返回值。根据返回类型的不同,Func 有不同的泛型变体。

代码示例:

demo1

Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(5, 3));

demo2

var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
foreach (var number in evenNumbers)
{
Console.WriteLine(number); // 输出 2 4 6
}

Predicate

Predicate 是一个特殊的委托类型,通常用于判断条件。它接受一个输入参数并返回一个布尔值。

代码示例:

demo1

Predicate<int> isEven = (num) => num % 2 == 0;
Console.WriteLine(isEven(4)); // 输出 True
Console.WriteLine(isEven(5)); // 输出 False
// ------------------------------------------------------------
static bool IsEven(int number)
{
return number % 2 == 0;
}
// 使用 Predicate 委托
Predicate<int> predicate = new Predicate<int>(IsEven);
Console.WriteLine(predicate(4));
Console.WriteLine(predicate(5));

demo2

var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.FindAll(new Predicate<int>(n => n % 2 == 0));
foreach (var number in evenNumbers)
{
Console.WriteLine(number); // 输出 2 4 6
}

Comparison

说明

//
// Summary:
// Represents the method that compares two objects of the same type.
//
// Parameters:
// x:
// The first object to compare.
//
// y:
// The second object to compare.
//
// Type parameters:
// T:
// The type of the objects to compare.
//
// Returns:
// A signed integer that indicates the relative values of x and y, as shown in the
// following table.
//
// Value – Meaning
// Less than 0 –x is less than y.
// 0 –x equals y.
// Greater than 0 –x is greater than y.
public delegate int Comparison<in T>(T x, T y);

代码示例

using System;
class Program
{
static void Main()
{
int[] numbers = { 5, 3, 8, 1, 2 };
Array.Sort(numbers, (x, y) => x.CompareTo(y));
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}

Convert

说明

//
// Summary:
// Represents a method that converts an object from one type to another type.
//
// Parameters:
// input:
// The object to convert.
//
// Type parameters:
// TInput:
// The type of object that is to be converted.
//
// TOutput:
// The type the input object is to be converted to.
//
// Returns:
// The TOutput that represents the converted TInput.
public delegate TOutput Converter<in TInput, out TOutput>(TInput input);

代码示例

using System;
class Program
{
static void Main()
{
string[] strings = { "1", "2", "3" };
int[] integers = Array.ConvertAll(strings, new Converter<string, int>(s => int.Parse(s)));
foreach (int num in integers)
{
Console.WriteLine(num);
}
}
}

相同点和不同点

  • 相同点:它们都是用来表示方法引用的类型。
  • 不同点delegate 是用户自定义的类型,
    Action, Func, 和 Predicate 是预定义的类型。
    Action 不返回任何值,
    Func 返回一个值(具体取决于泛型参数),
    Predicate 总是返回布尔值。
    此外,ActionFunc 提供了更多的灵活性来匹配不同的方法签名,而 Predicate 主要用于条件判断。
posted on   超级无敌美少男战士  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示