为什么此功能与此代理具有不兼容的签名?

时间:2011-10-26 20:12:53

标签: .net vb.net delegates

编译器告诉我这些签名是不兼容的,但它们对我来说似乎很好。我错过了什么吗? [VS 2008]

Public MustOverride Function OverridePickUpLocationFromDeliveryAddress(ByVal objDeliveryAddress As DeliveryLocationWS.DeliveryAddress, _
                                                                       ByRef lstProcessingMessages As List(Of String), _
                                                                       ByVal objProcessorHelperLists As ProcessorHelperLists) As Integer

Public Sub New()    
    Dim fncTest As Func(Of DeliveryLocationWS.DeliveryAddress, List(Of String), ProcessorHelperLists, Integer) = AddressOf OverridePickUpLocationFromDeliveryAddress
End Sub

2 个答案:

答案 0 :(得分:3)

您的函数通过引用(lstProcessingMessages)采用参数,这对于您尝试将其分配给Func(Of T1, T2, T3, T4)是不可接受的。

据我所知,Func委托不支持“by ref”作为类型参数。

static void Main()
{
    Func<int, int> myDoItFunc1 = DoIt; // Doesn't work because of ref param
    Func<int, int> myDoItFunc2 = DoItFunc; // Does work
}

public static int DoItFunc(int i)
{
    return DoIt(ref i);
}

public static int DoIt(ref int i)
{
    return 0;
}

但是你为什么要通过ref传递lstProcessingMessages呢?这是一种参考类型。您是期望完全替换列表的引用,还是只能清除并填充?

static void Main()
{
    var myList = new List<int>();

    AddToMyList(myList);

    // myList now contains 3 integers.

    ReplaceList(myList);

    // myList STILL contains 3 integers.

    ReplaceList(ref myList);

    // myList is now an entirely new list.
}

public static void AddToMyList(List<int> myList)
{
    myList.Add(1); // Works because you're calling "add"
    myList.Add(2); // on the *same instance* of my list
    myList.Add(3); // (object is a reference type, and List extends object)
}

public static void ReplaceList(List<int> myList)
{
    myList = new List<int>();
}

public static void ReplaceList(ref List<int> myList)
{
    myList = new List<int>();
}

答案 1 :(得分:0)

Func不起作用,因为参数声明为ByVal。但是,您可以声明自己的委托类型:

Delegate Function PickUpLocationDelegate(ByVal objDeliveryAddress As DeliveryLocationWS.DeliveryAddress, _
  ByRef lstProcessingMessages As List(Of String), _
  ByVal objProcessorHelperLists As ProcessorHelperLists) As Integer

Public Sub New()
    Dim fncTest As PickUpLocationDelegate = AddressOf OverridePickUpLocationFromDeliveryAddress
End Sub