2017-07-19 17 views
-1

我有一個抽象類的實現被傳遞到接受指定抽象類的通用T參數的函數中。但由於某種原因,它給我一個錯誤,說具體的類在給定的上下文中是無效的。具體類在作爲類型傳遞時在給定上下文中無效

任何想法最新什麼將不勝感激。

輔助方法

public static async Task<bool> StartSingleAppService<T>(T type) where T : Service 
    { 
     // GetServiceMaintainer() gets a singleton of my Services list 
     if (ServiceMaintainer.GetServiceMaintainer() != null) 
     { 
      Service service = ServiceMaintainer.GetServiceMaintainer().FindServiceByType(type); 
      if (await ServiceMaintainer.StartService(service)) 
      { 
       return true; 
      } 
     } 
     return false; 
    } 

用法

// `UpdateService` is type not valid in the given context 
await AppServices.StartSingleAppService(UpdateService); 

UpdateService

public class UpdateService : Service 

服務

public abstract class Service 

注:

  • Service抽象類定義的抽象任務的方法。 public abstract Task<bool> start();
  • Service抽象類定義了幾個成員變量
  • 的​​類實現的抽象方法和有幾個輔助函數。
+0

請張貼錯誤的全部內容,還有'UpdateService'變量的聲明。 –

+0

@JonB它不是一個變量。這是一個類被視爲類。錯誤無非就是我所說的。 – visc

+0

您是否正在使用'UpdateService'類的對象調用方法,或者您正將'UpdateService'類型傳遞給方法? –

回答

3

你已經把你的蘋果和梨稍加扭曲。由於它目前聲明,該方法不期望一個類型,它期望一個類型的實例。你可能想要做的是刪除參數並在你的方法中使用一個typeof-operator。

// argument removed here ------------------------------\/ 
public static async Task<bool> StartSingleAppService<T>() where T : Service 
{ 
    // GetServiceMaintainer() gets a singleton of my Services list 
    if (ServiceMaintainer.GetServiceMaintainer() != null) 
    { 
     Service service = ServiceMaintainer 
      .GetServiceMaintainer() 
      .FindServiceByType(typeof(T)); 
     // argument changed here --/\ 

     if (await ServiceMaintainer.StartService(service)) 
     { 
      return true; 
     } 
    } 
    return false; 
} 

調用點細微的變化也:

await AppServices.StartSingleAppService<UpdateService>(); 
+0

謝謝你做到了 – visc

相關問題