我很确定这是可能的,但我想要做的是有一个通用的方法,我可以传入一个对象和一个表达式,它将告诉方法在其逻辑中使用哪个属性。
有人能让我开始使用这样的语法吗?
基本上我想编码的是:
Dim firstNameMapper as IColumnMapper = new ColumnMapper(of Author)(Function(x) x.FirstName)
Dim someAuthorObject as new Author()
fistNameMapper.Map("Richard", someAuthorObject)
现在mapper对象会知道将FirstName属性设置为“Richard”。
现在在这里使用一个函数是行不通的,我知道这个......我只想弄清楚我正在努力的目标。
感谢您的帮助!
答案 0 :(得分:2)
您可以使用表达式树来实现此行为,但将ColumnMapper
稍微不同的函数传递会更简单。您可以为其设置一个设置属性值的函数,而不是使用读取属性的表达式:
Dim firstNameMapper as IColumnMapper = _
new ColumnMapper(of Author)(Sub(x, newValue) _
x.FirstName = newValue _
End Sub)
我认为这种语法在Visual Studio 2010中是新的(但我不是VB专家)。无论如何,参数的类型将是Action<Author, string>
,您只需在ColumnMapper
设置属性时随时调用它。
使用表达式树,你必须构造设置属性并在运行时编译它的表达式,所以我认为上面的其他几个代码是更容易解决问题的方法。
答案 1 :(得分:0)
好的,所以我已经实现了一个类似的解决方案(我没有使用2010,所以我不能直接使用Tomas的解决方案)但是虽然它编译,但似乎没有设置属性。以下是所有部分:
Module Module1
Sub Main()
Dim inputSource() As String = {"Richard", "Dawkins"}
Dim firstNameMapper As New ColumnMapper(Of Author)(Function(obj, value) obj.FirstName = value, 0)
Dim lastNameMapper As New ColumnMapper(Of Author)(Function(obj, value) obj.LastName = value, 1)
Dim theAuthor As New Author
firstNameMapper.map(inputSource, theAuthor)
lastNameMapper.map(inputSource, theAuthor)
System.Console.WriteLine(theAuthor.FirstName + " " + theAuthor.LastName)
System.Console.ReadLine()
End Sub
End Module
Public Class ColumnMapper(Of T As {Class})
Dim _propertyMapper As Action(Of T, String)
Dim _columnIndex As Int32
Public Sub New(ByVal mapAction As Action(Of T, String), ByVal columnNumber As Int32)
_propertyMapper = mapAction
_columnIndex = columnNumber
End Sub
Public Sub map(ByVal sourceFields As String(), ByRef destinationObject As T)
_propertyMapper(destinationObject, sourceFields(_columnIndex))
End Sub
End Class
Public Class Author
Private _firstName As String
Private _lastName As String
Public Property FirstName() As String
Get
Return _firstName
End Get
Set (ByVal value As String)
_firstName = value
End Set
End Property
Public Property LastName() As String
Get
Return _lastName
End Get
Set (ByVal value As String)
_lastName = value
End Set
End Property
End Class
知道为什么没有设置属性吗?
答案 2 :(得分:0)
不确定为什么使用内联'Function'的解决方案不起作用。也许更熟悉vb.net内部工作原理的人可以解释它,但是如果你实现下面的主模块,它就可以工作。感谢Tomas指出我正确的方向!
Module Module1
Sub Main()
Dim mapAction As Action(Of Author, String)
Dim inputSource() As String = {"Richard", "Dawkins"}
Dim firstNameMapper As New ColumnMapper(Of Author)(AddressOf setFirstName, 0)
Dim lastNameMapper As New ColumnMapper(Of Author)(AddressOf setLastName, 1)
Dim theAuthor As New Author
firstNameMapper.map(inputSource, theAuthor)
lastNameMapper.map(inputSource, theAuthor)
System.Console.WriteLine(theAuthor.FirstName + " " + theAuthor.LastName)
System.Console.ReadLine()
End Sub
Public Sub setFirstName(ByVal obj As Author, ByVal value As String)
obj.FirstName = value
End Sub
Public Sub setLastName(ByVal obj As Author, ByVal value As String)
obj.LastName = value
End Sub
End Module