调用泛型方法会产生编译器错误

时间:2012-12-13 10:14:17

标签: c# interface service-locator

我想在代码中解耦一些东西,这样我就不必在子项目中包含主项目中使用的DLL。为此,我创建了以下注册服务的方法(使用MS Common Practices Service Locator):

public static void RegisterService<TInterface>(SPSite site) where TInterface : IServiceLocatorRegisterable, new()
        {
            GetServiceLocatorConfig(site).RegisterTypeMapping<IServiceLocatorRegisterable, TInterface>(typeof(TInterface).FullName);
            InvalidateCache();

所以,正如你所看到的,我创建了接口“IServiceLocatorRegisterable”,这样我就不会受特定的interace约束。

在子项目中,我有一个特定的接口,我想在服务定位器中注册,所以我在声明中添加了“IServiceLocatorRegisterable”:

public interface ISapProcess : IServiceLocatorRegisterable
{ // details omitted.. }

这是我尝试注册此界面的代码:

public static void RegisterSapProcess(SPSite site)
{
    ServiceLocator.RegisterService<ISapProcess>(site);
}

但是我无法编译它,因为我得到了以下编译器错误:

  

ISapProcess必须是具有公共无参数的非抽象类型   构造函数,以便将其用作参数'TInterface'   泛型类型或方法'.... RegisterService(SPSite)'

..而且据我所知,当我尝试直接注册“基本接口”时,它也无法工作(当然这没有任何意义,因为我想注册并找到特定的接口/实现) :

ServiceLocator.RegisterService<IServiceLocatorRegisterable>(site);

我觉得我在这里缺少一些重要的东西。

1 个答案:

答案 0 :(得分:2)

好的 - 看看你的约束:

where TInterface : IServiceLocatorRegisterable, new()

你不能写:

ISapProcess x = new ISapProcess();
你能吗?这就是约束所需要的。

要么需要抛弃约束,要么改变你的类型参数。 (根据你提供的代码,目前还不清楚你要做什么。)

相关问题