C# 如何修复';属性是名称空间,但其使用方式与类型';C中的错误#

C# 如何修复';属性是名称空间,但其使用方式与类型';C中的错误#,c#,inheritance,attributes,C#,Inheritance,Attributes,我试图将“attribute”继承给一个类,但我做不到。基本上,我创建了一个新类RequiredPropertyAttribute,并尝试添加:属性来进行继承。但是,:属性有红色下划线 [AttributeUsage(Inherited =true)] class RequiredPropertyAttribute : Attribute //There is a problem. { } [AttributeUsage(

我试图将“attribute”继承给一个类,但我做不到。基本上,我创建了一个新类RequiredPropertyAttribute,并尝试添加:属性来进行继承。但是,:属性有红色下划线

       [AttributeUsage(Inherited =true)]
       class RequiredPropertyAttribute : Attribute //There is a problem.
       {

       }

       [AttributeUsage(AttributeTargets.Class,AllowMultiple = true)]
       class ToTableAttribute : Attribute //There is also a problem.
       {
           string _tableName;
           public ToTableAttribute(string tableName)
           {
               _tableName = tableName;
           }
       }
{}名称空间属性


“Attribute”是一个名称空间,但与类型一样使用。

您正在名为
Attribute
的名称空间中定义类

请尝试以下操作之一:

  • 将名称空间名称更改为其他名称

  • 继承自
    System.Attribute


  • 我假设这两个类所在的名称空间命名为
    Attribute
    ,因此完整代码为:

    namespace Attribute
    {
       [AttributeUsage(Inherited =true)]
       class RequiredPropertyAttribute : Attribute //There is a problem.
       {
    
       }
    
       [AttributeUsage(AttributeTargets.Class,AllowMultiple = true)]
       class ToTableAttribute : Attribute //There is also a problem.
       {
           string _tableName;
           public ToTableAttribute(string tableName)
           {
               _tableName = tableName;
           }
       }
    }
    
    如果不是这样,并且类不是名称空间的一部分,那么还有一个名称空间,在您的项目或引用的dll中,它的名称是
    Attribute
    。基本上,上述方法不起作用的原因是IntelliSense假设您的类继承自名为
    Attribute
    的命名空间,而不是类
    System.Attribute
    。因此,要解决此问题,您需要做的就是更改名称空间的名称或在冒号(
    System)后面加上
    属性的前缀。
    因此,您的固定代码如下所示:

    namespace Attribute //This should be renamed instead or else for every attribute class you create you will need to specify "System.Attribute" as the base
    {
       [AttributeUsage(Inherited =true)]
       class RequiredPropertyAttribute : System.Attribute //Will tell IntelliSense that your class is inheriting from the Attribute class rather than the above namespace
       {
    
       }
    
       [AttributeUsage(AttributeTargets.Class,AllowMultiple = true)]
       class ToTableAttribute : System.Attribute
       {
           string _tableName;
           public ToTableAttribute(string tableName)
           {
               _tableName = tableName;
           }
       }
    }
    

    为什么要在类定义中添加
    :属性
    ?你能解释一下你为什么那样做吗?你想从某人那里继承一些东西。你能告诉我们你想要继承什么吗?为什么你的命名空间被命名为
    属性
    ,因为它假定你试图从命名空间而不是类
    系统.Attribute
    继承。