gpt4 book ai didi

C# : how to create delegate type from delegate types?

转载 作者:太空狗 更新时间:2023-10-29 22:15:22 25 4
gpt4 key购买 nike

在 C# 中,如何创建将委托(delegate)类型映射到委托(delegate)类型的委托(delegate)类型?特别是,在我下面的示例中,我想声明一个委托(delegate) Sum 使得(借用数学符号)Sum(f,g) = f + g。然后我想调用 Sum(f,g)——例如 Sum(f,g)(5) [这意味着 f(5) + g (5)].

class  Example
{
delegate int IntToInt ( int i ) ;

public static int Double ( int i ) { return i * 2 ; }
public static int Square ( int i ) { return i * i ; }

delegate IntToInt IntToIntPair_To_IntToInt ( IntToInt f, IntToInt g ) ;

public static IntToInt Sum ( IntToInt f, IntToInt, g ) { return f + g ; }

public static void Main ( )
{
IntToInt DoubleInstance = Double ;
IntToInt SquareInstance = Square ;

IntToIntPair_To_IntToInt SumInstance = Sum ;

System.Console.WriteLine
( SumInstance ( DoubleInstance, SquareInstance ) ( 5 ) ) ;
// should print 35 = 10 + 25 = Double(5) + Square(5)
}
}

最佳答案

你只需要表达具体的类型。例如:

Func<Func<int, int>, Func<int, int>>

表示一个函数,它接受一个(将一个 int 转换为第二个 int 的函数)并返回一个(将一个 int 转换为第二个 int 的函数)。或者获取两个函数并返回第三个函数:

Func<Func<int, int>, Func<int, int>, Func<int, int>>

例如:

Func<Func<int, int>, Func<int, int>> applyTwice = (f => x => f(f(x));

这通常可以通过方法返回:

public static Func<Func<T,T>, Func<T,T>> ApplyTwice<T>()
{
return func => x => func(func(x));
}

如果你想对两个函数求和,你可以这样做:

public static Func<int, int> Sum(Func<int, int> first, Func<int, int> second)
{
return x => first(x) + second(x);
}

现在应用它:

Func<int, int> doubler = x => x * 2;
Func<int, int> squarer = x => x * x;
Func<int, int> doublePlusSquare = Sum(doubler, squarer);

Console.WriteLine(doublePlusSquare(5)); // Prints 35

(未经测试,但应该没问题...)


如果您没有可用的 C# 3 和 .NET 3.5,请声明以下委托(delegate):

public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg);
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

(我的 C# Versions page 上还有更多。)

然后你需要使用匿名方法,例如

public static Func<int, int> Sum(Func<int, int> first, Func<int, int> second)
{
return delegate(int x) { return first(x) + second(x); };
}

Func<int, int> doubler = delegate (int x) { return x * 2; };
Func<int, int> squarer = delegate (int x) { return x * x; };
Func<int, int> doublePlusSquare = Sum(doubler, squarer);

Console.WriteLine(doublePlusSquare(5)); // Prints 35

关于C# : how to create delegate type from delegate types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1177586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com