2017-07-19 48 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

相关问题