2012-09-19 67 views
3

我有此代碼具有[ENT]內的使用傳遞對象類型動態

public static void Retion() 
     { 

      using (Ent entitiesContext = new Ent()) 
       {...} 
     { 

我需要通過[ENT]動態地,這樣的:

public static void Retion(Type ds) 
      { 

       using (ds entitiesContext = new ds()) 
        {...} 
      { 

此的當然不起作用。如何更改此內容以便我可以動態傳遞它?

+0

什麼不行? – Tigran

+0

該類型很可能在組裝中。如果你正在動態加載它,那麼你必須設計這個類型來實現一個接口......它類似於遠程處理的工作方式。 – deostroll

回答

3

也許經由泛型調用構造從類型:

public static void Retion<T>() where T : IDisposable, new() 
{ 
    using (T entitiesContext = new T()) 
    {...} 

then Retion<Ent>()

注意,與entitiesContext做任何有用,你可能還需要一些基地 - 類約束,即

public static void Retion<T>() where T : DataContext, new() 
{ 
    using (T entitiesContext = new T()) 
    {...} 

當然,那那麼是不是巨大的差別來:

public static void Retion(Type type) 
{ 
    using (DataContext entitiesContext = 
     (DataContext)Activator.CreateInstance(type)) 
    {...} 
+0

+1「IDisposable」 – vlad

+0

由於基類約束,我接受這個。想知道除了DataContext基類約束之外是否還需要使用IDisposable? – user1662812

+0

@user取決於基類是否實現它 –

0

公共靜態無效Retion < T>(T DS)其中,T:新的() {

  using (T entitiesContext = new T()) 
       {...} 
     { 
0

可以通過反射

3

public static void Retion<T>() where T : IDisposable, new() 
    { 

      using (T entitiesContext = new T()) 
       {...} 
    } 
+0

對於'IDisposable' – vlad