我有一个与BeginDate和EndDate属性的许多类,我想要构建一个泛型方法,返回一个对象作为相同类型的列表,但与BeginDate=EndDate
。如何将Type.IsGenericTypeDefinition设置为true?
例:
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
为false的问题。
如何将其设置为true?
感谢您的重播,但没有帮助我:(,我对我的代码进行了一些更改,并面临另一个问题,它无法将匿名类型转换为泛型类型? – 2011-05-25 17:48:50
这解决了我的问题[http://www.codeproject。 com/KB/linq/AnonymousTypeTransform.aspx](http://www.codeproject.com/KB/linq/AnonymousTypeTransform.aspx) – 2011-05-25 18:11:17