[英]Using a method with generic parameters as a callback
Let's look at this situation:让我们看看这种情况:
private Func<int, int> callback;
public SomeClass(Func<int, int> callback)
{
this.callback = callback;
}
Then later we can call that function with稍后我们可以调用 function
callback(5);
and it would return a number.它会返回一个数字。
Now, what I want is something like the following现在,我想要的是类似下面的东西
private Func<T1, T2> callback;
public SomeClass(Func<T1, T2> callback)
{
this.callback = callback;
}
That delegate would accept a function with a signature like该代表将接受带有如下签名的 function
public T1 SomeFunc<T1, T2>(T2)
and could be called by并且可以被调用
callback<int, string>("hello")
which would return an int.这将返回一个 int。
Can this be done in C#?这个可以在C#做吗?
Sure, but you'll need to make the class generic as well.当然可以,但是您还需要使 class 通用。
Class SomeClass<T1, T2>
{
private Func<T1, T2> callback;
public SomeClass(Func<T1, T2> callback)
{
this.callback = callback;
}
}
If you're storing the callback locally, the easiest thing would be to make the class generic:如果您在本地存储回调,最简单的方法是使 class 通用:
public class SomeClass<TParam, TReturn>
{
private Func<TParam, TReturn> _callback;
public class SomeClass(Func<TParam, TReturn> callback)
{
_callback = callback;
}
}
Using properties you will have to make the class generic like the other posters said.使用属性,您必须像其他张贴者所说的那样使 class 通用。
It looks a little weird, but if you don't want your class to be generic then you could use generic methods to get and set the callback function, but the downside is that you will have to devise some way to keeping track of the types since you will need to pass them in to call call back.它看起来有点奇怪,但如果您不希望您的 class 是通用的,那么您可以使用通用方法来获取和设置回调 function,但缺点是您必须使用 devise 某种方式来跟踪类型因为您需要将它们传递给回调。 Not sure how useful this would actually be.
不确定这实际上有多大用处。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class CallbackTest
{
public CallbackTest(){}
private object _CallBack = null;
public Func<T1, T2> GetCallBack<T1,T2>()
{
return (Func<T1, T2>)_CallBack;
}
public void SetCallBack<T1, T2>(Func<T1, T2> value)
{
_CallBack = value;
}
}
class Program
{
static void Main(string[] args)
{
CallbackTest t = new CallbackTest();
t.SetCallBack(new Func<int, int>(x => x * x));
Console.WriteLine(t.GetCallBack<int, int>()(10));
t.SetCallBack(new Func<string, string>(x => x.ToUpper()));
Console.WriteLine(t.GetCallBack<string, string>()("test"));
Console.ReadLine();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.