如何将Type.IsGenericTypeDefinition设置为true
本文关键字:设置 true IsGenericTypeDefinition Type | 更新日期: 2023-09-27 17:57:35
我有一个具有BeginDate和EndDate属性的许多类,我想构建一个泛型方法,该方法将一个对象返回为相同类型但具有BeginDate=EndDate
的List。
例如:
项目开始日期=2011-05-01,项目结束日期=2011-05-03
结果必须是
项目1.开始日期=2011-05-01,项目1.结束日期=2011-05-01
项目2.开始日期=2011-05-02,项目2.结束日期=2011-05-02
项目3.开始日期=2011-05-03,第3项结束日期=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
是因为该类不是泛型的。只有你的方法是。
您应该能够反映类型并检索MethodInfo。然后可以使用MethodInfo.IsGenericMethod
或MethodInfo.IsGenericMethodDefinition
。
您的另一个选择是将类修改为泛型,但这太过分了,因为这是(我猜这里)唯一需要泛型参数的方法。
您不能设置此属性的值-它是只读的。