vb.net 中的多个泛型约束只允许访问第一类约束成员

问题描述

我在类上使用了 2 个泛型类型约束,我可以在 C# 代码获取这两种类型的所有成员,但 vb.net 中的相同实现只允许访问第一种类型约束的成员。

好像我在 vb.net 中使用了错误的语法,但不确定。

C# 示例代码

public class MainCaller<T> where T :  ITest,ITest2
{
    public void MainCallertest()
    {
        List<T> c = new List<T>();
        //Note:- here I am able to access the member of both the interfaces

        var x = c.FirstOrDefault(o => o.TestID == 1 && o.CommonID == 2);

    }
}

public interface ITest
{
    int TestID { get; set; }
}
public interface ITest2
{
    int CommonID { get; set; }
}

public class Classtest : ITest2,ITest
{
    public int TestID { get; set ; }
    public int CommonID { get; set; }
}

VB.net 示例代码

Friend Class MainCaller(Of T As ITest,ITest2)
    Public Sub MainCallertest()
        Dim c As List(Of T) = New List(Of T)()

        ''Note:- here I am able to access the member of only ITest interface
        ''       not the ITest2. (o.CommonID) is not accessible in below code

        Dim x = c.FirstOrDefault(Function(o) o.TestID = 1 Or o.CommonID = 2)

    End Sub
End Class

Interface ITest
    Property TestID As Integer
End Interface
Interface ITest2
    Property CommonID As Integer
End Interface

Public Class Classtest
    Implements ITest2,ITest

    Public Property TestID As Integer Implements ITest.TestID
        Get
            Throw New NotImplementedException()
        End Get
        Set(value As Integer)
            Throw New NotImplementedException()
        End Set
    End Property

    Public Property CommonID As Integer Implements ITest2.CommonID
        Get
            Throw New NotImplementedException()
        End Get
        Set(value As Integer)
            Throw New NotImplementedException()
        End Set
    End Property
End Class

解决方法

通过只使用一个逗号,您表示第二个泛型类型参数。单个参数的多个约束必须用大括号分组:

Friend Class MainCaller(Of T As {ITest,ITest2})

您拥有的 VB 代码相当于这个 C#:

public class MainCaller<T,ITest2> where T : ITest