首页  >  文章  >  后端开发  >  C# 自定义属性

C# 自定义属性

王林
王林原创
2024-09-03 15:07:19993浏览

当我们了解什么是自定义属性时,我们必须了解属性。属性是元数据扩展,它将在运行时向 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