变量取决于 vb.net 中的函数

本文关键字:函数 net 取决于 vb 变量 | 更新日期: 2023-09-27 18:32:14

(我是一名 ASP.NET 程序员,主要使用VB,但也可以用C#编程)

我喜欢有一个充满关键字和函数名称的列表(t)。例如:

Dim MyList as new List(of MyFunctions)
MyList.add(new Myfunction("descr","DBGetDescription()"))
MyList.add(new Myfunction("Name","DBGetName()"))
MyList.add(new Myfunction("create","DBGetCreateTS()"))
Public Class Myfunctions
  Public code     as String
  Public function as String
  Public Sub new(in_code as String, in_function as String)
    code = in_code
    function = in_function
  End Sub
End Class
'what do i want to search for:
Dim ToDo as String = "descr"
'search for it
Dim ThisFunction as MyFunction = MyList.find(function(x) x.code = ToDo)
'answer in 'thisfunction' gives me the name of the function i need to use
Dim FunctionIWantToUse = ThisFunction.function

(DBGetDescription、DBGetName 和 DBGetCreateTS 是现有的例程)
我知道我想启动的函数(例程)的名称,但它在一个变量中。
是否可以在 VB(或 C#)中启动函数?
有解决方法吗?

米.

变量取决于 vb.net 中的函数

您可以定义一个基本上是对函数的引用的delegate。这允许您将"名称"映射到实际函数,以便从字符串名称调用函数。

Delegate Function MyDelegateType() as string
Sub Main
    ' Create a dictionary mapping string names to the corresponding function.'
    ' Ive used a dictionary in my sample code, as its more straightforward, '
    ' but it would be trivial to wrap the name/function tuple up in a class and use a list'
    Dim MyList as new Dictionary(of string, MyDelegateType)
    MyList.Add("descr", addressof DBGetDescription)
    MyList.add("Name", addressof DBGetName)
    MyList.add("create", addressof DBGetCreateTS)
    ' Get the function for a key, and call it.'        
    Console.WriteLine(MyList.Item("descr")())
End Sub
Function DBGetDescription() as string
    return "MyDescription"
End Function
Function DBGetName() as string
    return "MyName"
End Function
Function DBGetCreateTS() as string
    return "MyCreateTS"
End Function