首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为AddressOf CalledBack添加代表?

如何为AddressOf CalledBack添加代表?
EN

Stack Overflow用户
提问于 2020-05-17 00:24:53
回答 1查看 115关注 0票数 0

尝试添加一个代理...unsuccesfully。

代码语言:javascript
复制
   Public Function CallbackAddress() As Integer
  'UPGRADE_WARNING: Add a delegate for AddressOf CalledBack Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="E9E157F7-EF0C-4016-87B7-7D7FBBC6EE08"'
    CallbackAddress = GetAddress(AddressOf CalledBack)
    End Function

    Private Function GetAddress(ByVal address As Integer) As Integer
        'GetAddress = address
        Return address
    End Function

以下是添加委托的失败(不完全或完全错误)尝试:

代码语言:javascript
复制
  Public Delegate Sub CalledBackDelegate(ByVal param As Integer)

  Public Function CallbackAddress() As Integer
        Dim myCalledBackDelegate As CalledBackDelegate = New CalledBackDelegate(AddressOf CalledBack)
        CallbackAddress = GetAddress(myCalledBackDelegate)  // << This doesn't work! 
    End Function

仍然有一个错误:

myCalledbackDegate不能转换为整数。

我遗漏了什么?

EN

回答 1

Stack Overflow用户

发布于 2020-05-18 01:55:55

这三个提议的函数都是返回整数的函数。当然,虽然有一个返回委托的函数是可能的,但是有一个返回固定的委托的函数将是毫无意义的。

委托是对函数的引用,用于调用在调用站点不知道要调用的方法的函数。现在更常用的是lambda函数。下面是一个完整的应用程序,它展示了委托和lambdas (一种特定类型的委托)是如何被普遍使用的。您的例子缺少用法,因此我们无法真正帮助您。希望这有助于澄清这一概念。(请原谅布局,使用iPad)。

代码语言:javascript
复制
imports System

Public Module Module1
  Public Sub Main()

    console.Write("Enter a number:")
    Dim x as integer = if(integer.tryparse(console.ReadLine().trim, x), x, x)
    console.Write("Enter another number:")
    dim y as integer = if(integer.tryparse(console.ReadLine().trim, y), y, y)

    console.Write("Enter a plus or minus sign:")

    dim operation = console.ReadLine().Trim()

    dim op as func(Of integer, integer, integer)

    select case operation
        case "+"
            op = addressof add
        case "-"
            op = addressof minus
    end Select
    Dim result = op(x, y)


    console.WriteLine($"Result of {x} {operation} {y} is {result}")

    dim lambda as func(of integer)

    select case operation
        case "+"
            lambda = function() x + y
        case "-"
            lambda = function() x - y
    end select 

    result =lambda()
    console.writeline($"Result of {x} {operation} {y} is {result}")

  End Sub
  public Function Add(x as integer, y as integer) as integer

    return x + y

  end Function

  public function Minus(x as integer, y as integer) as integer
    return x - y
  end function
End Module
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61845415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档