Public Class NodeInfo
Public Property X As Double
End Class
Public Class NetNode
Public Property X As Double
End Class
對于上面的模型,我有下面的地圖。源物件的“X”屬性值為 0.00013。我希望“o”的值相同,但它始終為 0。如果我回傳“sX”而不是“o”,它作業正常,但我認為 TMember 也應該回傳相應的屬性值。
CreateMap(Of NodeInfo, NetNode)().
ForMember(Function(n) n.X,
Sub(opt As IMemberConfigurationExpression(Of NodeInfo, NetNode, Double))
opt.MapFrom(Function(s As NodeInfo, d As NetNode, o As Double, ctx As ResolutionContext)
Return o
End Function)
End Sub).ReverseMap()
我正在使用以下多載。
IMemberConfigurationExpression<TSource, TDestination, TMember>
MapFrom<TResult>(Func<TSource, TDestination, TMember, ResolutionContext, TResult> mappingFunction);
所以我對該多載的完整表達如下:
Sub IMemberConfigurationExpression(Of NodeInfo,NetNode,Double).MapFrom(Of Double)(mappingFunction As Func(Of NodeInfo,NetNode,Double,ResolutionContext,Double))
有人可以解釋一下我錯過了什么嗎?
uj5u.com熱心網友回復:
原來 hat TMember 代表目標物件的目標成員。
感謝pfx對這個問題的回答。
因為我需要 ForAllMembers 中的源成員和目標成員,
1- 我通過 opt.DestinationMember 從 ForAllMembers 檢索目標成員
Sub(opt As IMemberConfigurationExpression(Of TSource, TDestination, Object))
Dim destinationProperty = TryCast(opt.DestinationMember, PropertyInfo)
Dim destinationProperty = TryCast(opt.DestinationMember, PropertyInfo)
If destinationProperty Is Nothing Then Return
Dim pd = TypeDescriptor.GetProperties(destinationProperty.DeclaringType).OfType(Of PropertyWithParamDescriptor).FirstOrDefault(Function(p) p.Name = destinationProperty.Name)
If pd IsNot Nothing AndAlso pd.CanWrite AndAlso pd.Unit IsNot Nothing AndAlso sourceType.GetProperty(destinationProperty.Name) IsNot Nothing Then
Dim unit = pd.Unit
2- 使用 ConvertUsing 到達源成員,并將目標成員作為引數提供給我在 ConvertUsing 中使用的方法。
opt.ConvertUsing(New UnitConvertor(Of Double)(destinationProperty, GetType(TSource), unit))
單位轉換器
Public Class UnitConvertor(Of T As Structure)
Implements IValueConverter(Of T, Object)
Dim _PropertyInfo As PropertyInfo
Dim _SourceType As Type
Dim _Unit As UnitAttribute
Public Sub New(propertyInfo As PropertyInfo, sourceType As Type, unit As UnitAttribute)
_PropertyInfo = propertyInfo
_SourceType = sourceType
_Unit = unit
End Sub
Public Function Convert(sourceMember As T, ctx As ResolutionContext) As Object Implements IValueConverter(Of T, Object).Convert
Dim unitName = ctx.GetUnitName(_SourceType, _PropertyInfo.Name)
Dim tUnit = If(unitName.HasValue, New Units(_Unit.Unit.UnitType, unitName), CType(Nothing, Units))
Return CType(If(tUnit?.C2SIUnit(System.Convert.ToDouble(sourceMember)), sourceMember), T)
End Function
End Class
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515504.html
