问题描述
|
我有一个带有BeginDate和EndDate属性的类,我想构建一个通用方法,该方法将一个对象返回为相同类型的List,但带有
BeginDate=EndDate
。
例如:
Item.BeginDate = 2011-05-01,
Item.EndDate = 2011-05-03
结果必须是
Item1.BeginDate = 2011-05-01,
Item1.EndDate = 2011-05-01
Item2.BeginDate = 2011-05-02,
Item2.EndDate = 2011-05-02
Item3.BeginDate = 2011-05-03,
Item3.EndDate = 2011-05-03
我尝试了以下代码
<Extension()> _
Public Function GetRatesPerDay(Of T As Class)(ByVal oldRatesList As List(Of T)) As List(Of T)
If oldRatesList Is Nothing OrElse oldRatesList.Count = 0 Then
Return New List(Of T)
End If
Dim ratesInDays As New List(Of T)
Dim oldBeginDate = oldRatesList.Where(Function(D) D IsNot Nothing).Min(Function(D) GetType(T).GetProperty(\"BeginDate\",GetType(DateTime)).GetValue(D,Nothing))
Dim oldEndDate = oldRatesList.Where(Function(D) D IsNot Nothing).Max(Function(D) GetType(T).GetProperty(\"EndDate\",Nothing))
Dim currentDay As DateTime = oldBeginDate
Dim typeArgs() As Type = {GetType(DateTime),GetType(DateTime),GetType(Nullable(Of Double)),GetType(String),GetType(HUMPSBaseClasses.RoomRateType)}
Dim constructed As Type = GetType(T).MakeGenericType(typeArgs)
While currentDay <= oldEndDate
Dim dayRate = (From D In oldRatesList _
Where D IsNot Nothing _
AndAlso currentDay >= GetType(T).GetProperty(\"BeginDate\",Nothing) _
AndAlso currentDay <= GetType(T).GetProperty(\"EndDate\",Nothing) _
Select New With {.NightRate = GetType(T).GetProperty(\"NightRate\",GetType(Nullable(Of Double))).GetValue(D,Nothing),_
.RatePlanID = GetType(T).GetProperty(\"RatePlanID\",GetType(System.String)).GetValue(D,_
.RoomRateType = GetType(T).GetProperty(\"RoomRateType\",GetType(HUMPSBaseClasses.RoomRateType)).GetValue(D,Nothing) _
}).SingleOrDefault()
If dayRate IsNot Nothing Then
Dim tempRate As Object = Activator.CreateInstance(constructed)
tempRate = New With {.BeginDate = currentDay,_
.EndDate = currentDay,_
.NightRate = dayRate.NightRate,_
.RatePlanID = dayRate.RatePlanID,_
.RoomRateType = dayRate.RoomRateType}
ratesInDays.Add(tempRate)
End If
currentDay = currentDay.AddDays(1)
End While
Return ratesInDays
End Function
但是我面临一个问题,即我的课程中有2分是错误的。
如何将其设置为true?
解决方法
你不能。那是一个只读属性。
由于该类不是通用类,因此您会获得3分。只有您的方法。
您应该能够反映类型并检索您的MethodInfo。然后可以使用
MethodInfo.IsGenericMethod
或MethodInfo.IsGenericMethodDefinition
。
您的另一种选择是将类修改为通用类,但这将是多余的,因为(我在这里猜测)这是唯一需要通用参数的方法。
,您无法设置此属性的值-它是只读的。