2011-10-10 70 views
0

我正在使用LINQ to Entities在VB.Net中生成類型化的結果集。我有一個通用的報告類,如下所示:在.net中運行時動態設置類型in .Net

Public Class Report 
    Public Property Name As String 
    Public Property SQL As String 
    Public Property Type As String 
End Class 

然後在呼叫範圍內我希望有代碼,不會是這樣的:

' create my data context 
Dim context As New MyAppEntities 
' get a report object out of a dropdown list 
Dim rpt as Report = CType(aComboBox.SelectedItem, Report) 
' create a result object based on the type stored in the object 
Dim res As ObjectResult(Of rpt.Type) = context.ExecuteStoreQuery(Of rpt.Type)(rpt.SQL) 

到目前爲止,我發現,淨贏不要讓我在運行時在(Of Type)子句中設置類型。

有誰知道如何做到這一點?

我試着將Report類的Type屬性更改爲Type類型的對象,但這也不起作用。

順便說一句,我知道有其他的方法來完成同樣的事情,但我正在處理外部約束,這使我現在必須處理。無論如何,直覺上這樣的東西應該可以工作,我想弄清楚如何。

+0

您是否試圖動態指定泛型類型參數?我認爲你需要使用反射。請參閱http://stackoverflow.com/questions/196936/reflection-and-generic-types。 –

回答

1

下面是在C#中的答案:

Creating a Generic<T> type instance with a variable containing the Type

相關的方法和代碼:

var genericListType = typeof(List<>); 
var specificListType = genericListType.MakeGenericType(typeof(double)); 
var list = Activator.CreateInstance(specificListType); 

在這種情況下,你會使用ObjectResult代替List。希望有所幫助。

0

有了嚴格的選項你不能這樣做。嚴格執行靜態類型。與靜態類型,你必須堅持使用對象,但如果你刪除嚴格的選項,你可以完成動態輸入vb.net 請參閱this問題