首頁  >  文章  >  後端開發  >  C# 自訂屬性

C# 自訂屬性

王林
王林原創
2024-09-03 15:07:19989瀏覽

當我們了解什麼是自訂屬性時,我們必須了解屬性。屬性是元資料擴展,它將在運行時向 C# 編譯器提供有關 C# 程式中元素的附加資訊。這些屬性用於放置條件或增加程式碼的可讀性和效率。 C#(C Sharp)中存在許多預先定義屬性,而且我們還可以建立稱為「自訂屬性」的新使用者屬性。要建立自訂類,我們必須從 System.屬性類。

自訂屬性在 C# 中如何運作?

C# 自訂屬性是基於用於建構的預定義類別來運作。我們將逐步研究如何建立自訂屬性。建立自訂屬性的步驟:

步驟#1

透過使用AttributeUsageAttribute標籤:AttributeUsageAttribute標籤用於建構屬性。此標記也用於確定目標屬性是什麼以及是否可以繼承或屬性的多個物件或實例是否可以存在。此 AttributeUsageAttribute 標籤有 3 個主要成員

  • AttributeUsageAttribute( AttributeTargets.All)
  • AttributeUsage(AttributeTargets.All, Inherited = false)
  • AttributeUsage(AttributeTargets.Method,AllowMultiple = true)

1。 AttributeUsageAttribute(AttributeTargets.All): AttributeTargets.All 指定該屬性可以應用於程式的所有其他部分,而Attribute.該類別將指示它應應用於該類,並將AttributeTargets.Method 參數應用於自訂方法。

文法:

AttributeUsageAttribute( AttributeTargets.All)

2。 AttributeUsage(AttributeTargets.All, Inherited = false): 從此 AttributeUsageAttribute( AttributeTargets.All) 是繼承成員,它表示自訂屬性可以繼承或不繼承。 Inherited = false 是布林值 true/false。如果我們沒有指定 Inherited = true/false 那麼預設值為 true。

文法:

AttributeUsage(AttributeTargets.All, Inherited = false)

3。 AttributeUsage(AttributeTargets.Method, AllowMultiple = true): 從這個AllowMultiple參數告訴我們該屬性是否存在多個物件。它還採用布林值。預設情況下,該布林值為 false。

文法:

AttributeUsage(AttributeTargets.Method, AllowMultiple = true)

步驟#2

1。透過定義屬性類別:這更多或類似於普通的類別定義。類別名稱是屬性中約定的結尾。此屬性類別繼承自System.屬性類別。

文法:

[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class MyAttributeDefinition: Attribute
{
//some logic or methods
}

步驟#3

1。定義屬性與建構子: 定義建構子與所有其他類別建構子類似,用於設定預設值,Properties 用於定義資料庫連線名稱資訊、靜態資訊等

文法 #1

public MyAttribute(dataType dataTypeValue)
{
this.dataTypeValue= dataTypeValue;
}
注意:自訂屬性具有用於取得和設定資料類型變數的屬性。

文法#2

public dataType Properties
{
get {return this.dataTypeValue;}
set {this.value = presentValue;}
}

實作 C# 自訂屬性的範例

以下是提到的範例:

範例#1

帶有 typeOf 運算子的自訂屬性

代碼:

// including packages
using System;
using System.Reflection;
using System.Collections.Generic;
// Creating a custom class from Attribute class
class CustomAttribute : Attribute {
// private variables declaration
private string name;
private string company;
//parameterized class CustomAttribute constuctor
public CustomAttribute(string name, string company)
{
this.name = name;
this.company = company;
}
// method to display the fields by using reflection class
public static void AttributeDisplay(Type classType)
{
Console.WriteLine("All the Methods of the class {0} are", classType.Name);
//methods of the class for store all the attribute values
MethodInfo[] methods = classType.GetMethods();
//looping through method attribute values by using for loop
for (int i = 0; i < methods.GetLength(0); i++) {
//create the array to recieve all the custom attribute values
object[] attributesArray = methods[i].GetCustomAttributes(true);
// foreach loop to read the values through all attributes of the method
foreach(Attribute item in attributesArray)
{
if (item is CustomAttribute) {
//display the custom attribute values
CustomAttribute attributeObject = (CustomAttribute)item;
Console.WriteLine("{0} - {1}, {2} ", methods[i].Name,
attributeObject.name, attributeObject.company);
}
}
}
}
}
//Employer class to create employer fields
class Employer {
//employer fields declaration
int employeeID;
string name;
//Parameterized Employer class constructor
public Employer(int eID, string name)
{
this.employeeID = eID;
this.name = name;
}
// Applying the custom attribute for CustomAttribute for the  getId method
[CustomAttribute("Accessor Values", "Generates employee ID")] public int getEmployeeID()
{
return employeeID;
}
// Applying the custom attribute to CustomAttribute for the getName method
[CustomAttribute("Accessor Values", "Generates employee ID")] public string getName()
{
return name;
}
}
//create employee class
class Employee {
//Declaring variables of Employee
int employeeID;
string name;
//Parameterized Employee constructor
public Employee(int eID, string name)
{
this.employeeID = eID;
this.name = name;
}
// Applying the custom attribute CustomAttribute for the getEmployeeID method
[CustomAttribute("Accessor Values", "Generates employee ID")] public int getEmployeeID()
{
return employeeID;
}
// Applying the custom attribute CustomAttribute for the getName method
[CustomAttribute("Accessor Values", "Generates employee ID")] public string getName()
{
return name;
}
}
//create a class for display the output
public class Program {
// main method for the application
public static void Main(string[] args)
{
//calling static method for display typeOf employer class
CustomAttribute.AttributeDisplay(typeof(Employer));
Console.WriteLine();
//calling static method for display typeOf employee class
CustomAttribute.AttributeDisplay(typeof(Employee));
}
}

輸出:

C# 自訂屬性

範例#2

帶有員工詳細資料的自訂屬性

代碼:

using System;
[AttributeUsage(AttributeTargets.All)]
class CustomAttribute : Attribute {
private string name;
private string designation;
// Constructor
public CustomAttribute(string name, string designation)
{
this.name = name;
this.designation = designation;
}
// setters and getters
public string Name
{
get { return name; }
}
// property to get designation
public string Action
{
get { return designation; }
}
}
class Employee {
private int empID;
private string empName;
private double salary;
[CustomAttribute("Modifier", "Assigns the Employee Details")]
public void setDetails(int id,string name, double sal)
{
empID = id;
empName = name;
salary=sal;
}
[CustomAttribute("It is an Accessor", "Displays empID")] public int getEmpID()
{
return empID;
}
[CustomAttribute("It is an Accessor", "Displays empID")] public string getEmpName()
{
return empName;
}
[CustomAttribute("It is an Accessor", "Displays empID")] public double getSalary()
{
return salary;
}
}
public class EmployeeDetailsOut {
// main method for run the application
//main method modifier must be public
public static void Main(string[] args)
{
Employee emp = new Employee();
emp.setDetails(2424, "Paramesh", 400000.00);
Console.WriteLine("Employee Details");
Console.WriteLine("Employee ID Number : " + emp.getEmpID());
Console.WriteLine("Employee Name : " + emp.getEmpName());
Console.WriteLine("Employee Salary : " + emp.getSalary());
Console.WriteLine("\n");
Employee emp1 = new Employee();
emp1.setDetails(2423, "Amardeep", 600000.00);
Console.WriteLine("Employee Details");
Console.WriteLine("Employee ID Number : " + emp1.getEmpID());
Console.WriteLine("Employee Name : " + emp1.getEmpName());
Console.WriteLine("Employee Salary : " + emp1.getSalary());
}
}

輸出:

C# 自訂屬性

範例 #3

自訂屬性示範

代碼:

using System;
using System.Diagnostics;
public class DemonstrationOfCustomAttribute {
[Conditional("DEBUG")]
public static void getMyOut(string msg) {
Console.WriteLine(msg);
}
}
public class Test {
static void firstMethod() {
DemonstrationOfCustomAttribute.getMyOut("I am first method.");
secondMethod();
}
static void secondMethod() {
DemonstrationOfCustomAttribute.getMyOut("I am second method.");
}
public static void Main() {
DemonstrationOfCustomAttribute.getMyOut("I am in main method.");
firstMethod();
}
}

輸出:

C# 自訂屬性

結論

C# 中的自訂屬性用於定義類別的已宣告實作。我們可以通過 3 個步驟來實現這個自定義屬性,即使用 AttributeUsageAttribute、AttributeUsage (AttributeTargets.All, Inherited = false 和 AttributeUsage (AttributeTargets.Method, AllowMultiple = true)。

以上是C# 自訂屬性的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:C# 命令列參數下一篇:C# 命令列參數