命名空间/类型编译器错误

时间:2015-08-12 09:17:00

标签: c# web-services

我有一个C#,里面有一个类

namespace TestBL
{
    public class Test
    {
        public int Id { get; set; }
        public string PostedBy { get; set; }
        public string Text { get; set; }
    }
}

然后我添加一个WebService:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using TestBL;

namespace Test.WebService
{
    [ServiceContract]
    public interface ITestService
    {
         [OperationContract]
         IList<Test> GetTest();
    }
}

每次我尝试使用Test类时,都会返回错误:

'Test' is a 'namespace' but is used like a 'type'

我没有看到我在哪里使用Test作为命名空间,我的命名空间和类名也不同。

编辑:另外,我知道我可以让它像

一样工作
IList<TestBL.Test>

但我想知道为什么我会收到错误。

4 个答案:

答案 0 :(得分:1)

您的ITestService界面位于Test.WebService命名空间中。这意味着Test是一个命名空间。是的我知道命名空间的名称是Test.WebService但是C#编译器用点分隔命名空间名称,因此Test是命名空间,而WebService是Test中的命名空间。

当你尝试使用Test类时,编译器是如此愚蠢以至于它认为你正在尝试编写一个名称,这就是错误发生的原因。

要点:

发生错误只是因为编译器认为Test是命名空间,而在该命名空间中,有一个名为WebService的命名空间。获取它?换句话说,C#编译器很傻(我只是在开玩笑)

答案 1 :(得分:1)

这是命名空间测试 -

 namespace Test.WebService // namepace WebService inside namespace Test.

它也是一个类 -

public class Test.

编译器不知道你使用哪一个,改变了类名。

答案 2 :(得分:0)

您正在使用嵌套命名空间Test.WebService,它等同于:

namespace Test
{
    namespace WebService
    {
        [ServiceContract]
        public interface ITestService
        {
             [OperationContract]
             IList<Test> GetTest();
        }
    }
}

外部命名空间(Test)导致与Test类命名冲突。

答案 3 :(得分:0)

我还想补充一点,作为一种解决方法而不更改任何名称,可以简单地将using TestBL移动到命名空间内,如下所示:

namespace Test.WebService
{
    //other using
    using TestBL;

    [ServiceContract]
    public interface ITestService
    {
         [OperationContract]
         IList<Test> GetTest();
    }
}

这不会返回错误,因为我发现,也许有人会发现这有用。