将 Swift 完成闭包转换为 C#
Converting a Swift Completion Closure to C#
我正在将库从 Swift 移植到 C#,但在将完成处理程序转换为 C# 时遇到问题。
在Swift我有:
public typealias myChangeHandler = (progress: Double, myView: MyCustomView)
private var myChangeClosure: myChangeHandler?
public func myChangeClosure(_ completion: myChangeHandler) {
myChangeClosure = completion
}
可以这样调用:
myChangeClosure?(progress: myProgress, view: self)
或者像这样:
localInstance.myChangeClosure() {
(progress: Double, myView: MyCustomView) in
textLabel.text = "\(Int(progress * 100.0))%"
}
在 C# 中,我尝试过这样的操作:
Func<double, MyCustomView> MyChangeType;
public void MyChangeClosure(Func<double, MyCustomView> completion)
{
MyChangeType = completion;
}
我无法使用与 Swift:
类似的语法调用
MyChangeType(myProgress, (MyCustomView)this); // bad job :'(
我的问题
如何将上面的 Swift 完成功能转换为 C#?
Func 第一个泛型是 return 类型,在您的例子中是 double。你想要的是使用一个动作:
Action<double, MyCustomView> MyChangeType;
然后你就可以随心所欲地使用它了:
MyChangeType(myProgress, (MyCustomView)this); // good job :)
你可以看看这个网页进一步解释:
http://www.c-sharpcorner.com/blogs/delegate-vs-action-vs-func1
我正在将库从 Swift 移植到 C#,但在将完成处理程序转换为 C# 时遇到问题。
在Swift我有:
public typealias myChangeHandler = (progress: Double, myView: MyCustomView)
private var myChangeClosure: myChangeHandler?
public func myChangeClosure(_ completion: myChangeHandler) {
myChangeClosure = completion
}
可以这样调用:
myChangeClosure?(progress: myProgress, view: self)
或者像这样:
localInstance.myChangeClosure() {
(progress: Double, myView: MyCustomView) in
textLabel.text = "\(Int(progress * 100.0))%"
}
在 C# 中,我尝试过这样的操作:
Func<double, MyCustomView> MyChangeType;
public void MyChangeClosure(Func<double, MyCustomView> completion)
{
MyChangeType = completion;
}
我无法使用与 Swift:
类似的语法调用MyChangeType(myProgress, (MyCustomView)this); // bad job :'(
我的问题
如何将上面的 Swift 完成功能转换为 C#?
Func 第一个泛型是 return 类型,在您的例子中是 double。你想要的是使用一个动作:
Action<double, MyCustomView> MyChangeType;
然后你就可以随心所欲地使用它了:
MyChangeType(myProgress, (MyCustomView)this); // good job :)
你可以看看这个网页进一步解释:
http://www.c-sharpcorner.com/blogs/delegate-vs-action-vs-func1