Wrapper class for a Predicate(Of T) (C#版本)
public delegate bool PredicateWrapperDelegate<T, A>(T item, A argument);
public class PredicateWrapper<T, A>
{
private A _argument;
private PredicateWrapperDelegate<T, A> _wrapperDelegate;public PredicateWrapper(A argument, PredicateWrapperDelegate<T, A> wrapperDelegate)
{
_argument = argument;
_wrapperDelegate = wrapperDelegate;
}private bool InnerPredicate(T item)
{
return _wrapperDelegate(item, _argument);
}
public static implicit operator Predicate<T>(PredicateWrapper<T, A> wrapper)
{
return new Predicate<T>(wrapper.InnerPredicate);
}}
Wrapper class for a Predicate(Of T) (vb.net版本)
Code:
Public Delegate Function PredicateWrapperDelegate(Of T, A) _
(ByVal item As T, ByVal argument As A) As BooleanPublic Class PredicateWrapper(Of T, A)
Private _argument As A
Private _wrapperDelegate As PredicateWrapperDelegate(Of T, A)Public Sub New(ByVal argument As A, _
ByVal wrapperDelegate As PredicateWrapperDelegate(Of T, A))_argument = argument
_wrapperDelegate = wrapperDelegate
End SubPrivate Function InnerPredicate(ByVal item As T) As Boolean
Return _wrapperDelegate(item, _argument)
End FunctionPublic Shared Widening Operator CType( _
ByVal wrapper As PredicateWrapper(Of T, A)) _
As Predicate(Of T)Return New Predicate(Of T)(AddressOf wrapper.InnerPredicate)
End OperatorEnd Class
Generic user class I used for testing.
Code:
Public Class User
Public Sub New(ByVal firstName As String, ByVal lastName As String)
Me._firstName = firstName
Me._lastName = lastName
End SubPrivate _firstName As String
Public Property firstName() As String
Get
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value
End Set
End Property
Private _lastName As String
Public Property lastName() As String
Get
Return _lastName
End Get
Set(ByVal value As String)
_lastName = value
End Set
End PropertyEnd Class
Example usage where I pass a search parameter 'Jim' in for the first name.
Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim userList As New List(Of User) _
(New User() {New User("Jim", "Smith"), New User("John", "Doe"), New User("Bill", "Jones")})
Dim searchedUser As User = _
userList.Find(New PredicateWrapper(Of User, String)("Jim", AddressOf FirstNameMatch))
End SubPrivate Function FirstNameMatch(ByVal item As User, ByVal searchArg As String) As Boolean
Return item.firstName.Equals(searchArg)
End FunctionEnd Class
System.Predicate 通用类 vb.net c#
最新推荐文章于 2023-02-15 02:45:41 发布