代码之家  ›  专栏  ›  技术社区  ›  Brian Webster Jason

VB.NET-有没有一种方法可以利用代理中的可选参数(或者计划允许这样做?)

  •  3
  • Brian Webster Jason  · 技术社区  · 15 年前

    但是,我想知道是否有任何解决办法或计划将此功能合并到VB.NET中?

    我想做的是:

    Public Delegate Function Deserializer(Of T)(ByRef Buffer() As Byte, optional ByRef BufferPosition As Integer = 0) As T 
    
    'Implementation of a func that matches the delegate'
    Class A
      Public Function Deserialize(Byref Buffer() as Byte, optional Byref BufferPosition as integer = 0)
      ....
    

    如果在实际委托本身中没有指定“optional”,那么至少可以在函数实现中这样做:

    Public Delegate Function Deserializer(Of T)(ByRef Buffer() As Byte, ByRef BufferPosition As Integer) As T 
    
    'Implementation of a func that matches the delegate'
    Class A
      Public Function Deserialize(Byref Buffer() as Byte, optional Byref BufferPosition as integer = 0)
      ....
    

    至少在第二种方式中,委托的函数总是有一个映射到每个参数的值,尽管有些可能来自函数端而不是调用端。

    3 回复  |  直到 15 年前
        1
  •  1
  •   Merlyn Morgan-Graham    15 年前

    我不想尝试编写一个代理签名来处理我感兴趣的所有案例,也不可能限制将来的灵活性(尽管这确实取决于案例……),而是有时使用一个操作(代理的签名不带参数)来代替编写我自己的代理:

    void SomeFunction(Action action)
    {
        // ...
        action();
    }
    

    int someValueFromLocalScope = 5;
    SomeFunction(() => DoSomethingElse(someValueFromLocalScope));
    
    // you can also assign a closure to a local variable:
    
    int someValueFromLocalScope = 5;
    Action doSomethingElse =
        delegate()
        {
            DoSomethingElse(someValueFromLocalScope);
        }; // Or you could use () => { } syntax...
    SomeFunction(doSomethingElse);
    

    然后,SomeFunction不需要知道哪些参数适用于特定的操作。

    (答案是关于闭包,但这可能也有帮助)

    http://msdn.microsoft.com/en-us/library/system.action.aspx

    就像其他委托一样,您也可以将Action用作成员变量。

    Action<TFirstParameter>
    Func<TReturnValue>
    Func<TFirstParameter, TReturnValue>
    

    等。

        2
  •  0
  •   jreed350z    12 年前

    在VB.net中,可以使用创建匿名委托。

    Sub(t1, t2) methodName(t2)

    这允许您选择不传入第一个参数。

        3
  •  -2
  •   gazarsgo    15 年前

    为什么不使用可为null的类型,也就是装箱,而不是使用可选参数呢?