📜  C#中的属性

📅  最后修改于: 2021-05-29 21:05:25             🧑  作者: Mango

在C#中使用属性来传达有关各种代码元素(例如方法,程序集,属性,类型等)的声明性信息或元数据。通过使用在顶部使用方括号([])放置的声明性标记将属性添加到代码中。所需的代码元素。 .NET Framework提供的属性实现有两种类型:

  1. 预定义属性
  2. 自定义属性

属性的属性:

  • 属性可以具有参数,就像方法,属性等一样可以具有参数。
  • 属性可以具有零个或多个参数。
  • 不同的代码元素(例如方法,程序集,属性,类型等)可以具有一个或多个属性。
  • 通过在运行时访问属性,可以使用反射来获取程序的元数据。
  • 属性通常是从System.Attribute类派生的。

1.预定义属性

预定义属性是属于.NET Framework类库的那些属性,并且C#编译器出于特定目的支持这些属性。从System.Attribute基类派生的一些预定义属性如下所示:

Attribute Description
AttributeUsageAttribute This attribute specifies the usage of a different attribute.
CLSCompliantAttribute This attribute shows if a particular code element complies with the Common Language Specification.
ContextStaticAttribute This attribute indicates if a static field value is unique for the specified context.
FlagsAttribute This attribute indicates if a static field value is unique for the specified context.
LoaderOptimizationAttribute This attribute sets the optimization policy for the default loader in the main method.
NonSerializedAttribute This attribute signifies that the field of the serializable class should not be serialized.
ObsoleteAttribute This attribute marks the code elements that are obsolete i.e. not in use anymore.
SerializableAttribute This attribute signifies that the field of the serializable class can be serialized.
ThreadStaticAttribute This attribute indicates that there is a unique static field value for each thread.
DllImportAttribute This attribute indicates that the method is a static entry point as shown by the unmanaged DLL.

让我们讨论一些预定义的属性:

CLSCompliantAttribute

此属性显示特定的代码元素是否符合公共语言规范。如果特定代码元素符合公共语言规范。如果不是,则编译器会发出警告消息。

示例1:在这里,它不会发出任何警告消息,并且代码可以成功编译。

// C# program to demonstrate CLSCompliantAttribute
using System;
  
// CLSCompliantAttribute applied to entire assembly
[assembly:CLSCompliant(true)]
  
    public class GFG {
  
    // Main Method
    public static void Main(string[] args)
    {
        Console.WriteLine("GeeksForGeeks");
    }
}
输出:
GeeksForGeeks

示例2:此代码将由编译器给出警告消息。

// C# program to demonstrate CLSCompliantAttribute
// giving a warning message
using System;
  
// CLSCompliantAttribute applied to entire assembly
[assembly:CLSCompliant(true)]
  
    public class GFG {
    public uint z;
}
  
class GFG2 {
  
// Main Method
public static void Main(string[] args)
{
    Console.WriteLine("GeeksForGeeks");
}
  
}

警告:

FlagsAttribute

FlagsAttribute指定可以将枚举用作一组标志。这最常与按位运算运算符。

例子:

// C# program to demonstrate FlagsAttribute
using System;
  
class GFG {
  
    // Enum defined without FlagsAttribute.
    enum Colours { Red = 1,
                   Blue = 2,
                   Pink = 4,
                   Green = 8
    }
  
    // Enum defined with FlagsAttribute.
    [Flags] enum ColoursFlags { Red = 1,
                                Blue = 2,
                                Pink = 4,
                                Green = 8
    }
  
    // Main Method
    public static void Main(string[] args)
    {
        Console.WriteLine((Colours.Red | Colours.Blue).ToString());
        Console.WriteLine((ColoursFlags.Red | ColoursFlags.Blue).ToString());
    }
}
输出:
3
Red, Blue

ObsoleteAttribute

ObsoleteAttribute标记过时的代码元素,即不再使用。调用这些过时的代码元素会导致编译器错误。

例子:

// C# program to demonstrate ObsoleteAttribute
using System;
  
class GFG {
  
    // The method1() is marked as obsolete
    [Obsolete("method1 is obsolete", true)] static void method1()
    {
        Console.WriteLine("This is method1");
    }
  
    static void method2()
    {
        Console.WriteLine("This is method2");
    }
  
    public static void Main(string[] args)
    {
        method1(); // Compiler error as method1() is obsolete
        method2();
    }
}

编译错误:

自定义属性

可以在C#中创建自定义属性,以便以任何所需的方式将声明性信息附加到方法,程序集,属性,类型等。这增加了.NET框架的可扩展性。

创建自定义属性的步骤:

  • 定义从System.Attribute类派生的自定义属性类。
  • 定制属性类名称应具有后缀Attribute
  • 使用属性AttributeUsage指定所创建的定制属性类的用法。
  • 创建构造函数和定制属性类的可访问属性。

    例子:

    // C# program to demonstrate Custom Attributes
    using System;
      
    // AttributeUsage specifies the usage
    // of InformationAttribute
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | 
                            AttributeTargets.Method, AllowMultiple = true)]
      
        // InformationAttribute is a custom attribute class
        // that is derived from Attribute class
        class InformationAttribute : Attribute
        {
            public string InformationString{ get; set; }
        }
      
    // InformationAttribute is used in student class
    [Information(InformationString = "Class")] public class student
    {
      
        private int rollno;
        private string name;
      
        [Information(InformationString = "Constructor")] public student(int rollno, string name)
        {
            this.rollno = rollno;
            this.name = name;
        }
      
        [Information(InformationString = "Method")] public void display()
        {
            Console.WriteLine("Roll Number: {0}", rollno);
            Console.WriteLine("Name: {0}", name);
        }
    }
      
    // Driver Class
    public class GFG {
      
        // Main Method
        public static void Main(string[] args)
        {
            student s = new student(1001, "Lily Adams");
            s.display();
        }
    }
    
    输出:
    Roll Number: 1001
    Name: Lily Adams