我有很多具有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", GetType(DateTime)).GetValue(D, 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", GetType(DateTime)).GetValue(D, Nothing) _
AndAlso currentDay <= GetType(T).GetProperty("EndDate", GetType(DateTime)).GetValue(D, 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, Nothing), _
.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
但是我遇到了Type.IsGenericTypeDefinition
我班级错误的问题。
如何将其设置为true?
答案 0 :(得分:2)
你做不到。这是一个只读属性。
你得到false
,因为这个类不是通用的。只有你的方法。
您应该能够反思类型并检索MethodInfo。然后,您可以使用MethodInfo.IsGenericMethod
或MethodInfo.IsGenericMethodDefinition
。
你的另一个选择是将类修改为通用类,但这样就太过分了,因为这是(我猜这里)唯一需要泛型参数的方法。
答案 1 :(得分:1)
您无法设置此属性的值 - 它是只读的。