c sharp 特性详解

文章目录

    • 一、特性基础用法
    • 二、常见的内置特性
    • 三、自定义特性
    • 四、通过反射读取特性
    • 五、实际应用场景
    • 六、练习

一、特性基础用法

什么是特性?
特性是一种继承System.Attribute类,用于标记代码元素
特性的语法:

[AttributeName(Parameter1, Parameter2, NamedParameter = Value)]
public class MyClass { /*...*/ }

二、常见的内置特性

  1. [Obsolete] - 标记过时代码
    用于标记方法、类等已过时,编译器会给出警告或错误。

            [Obsolete("该方法已过时,请用NewNethod()")]
            public void oldMeth()
            {
    
            }
            [Obsolete("该方法已移除")]
            public void DeprecatedMethod()
            {
    
            }
    
  2. [Serializable] - 序列化支持
    标记类可以被序列化(如转为 JSON 或二进制)。

            [Serializable]
            public class person
            {
               private string name { get; set; }
               private int age { get; set; }
            }
    
  3. [DllImport] - 调用非托管代码
    用于调用外部 DLL 中的函数。

    using System.Runtime.InteropServices;
    
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern int MessageBox(int hWnd, string text, string caption, int options);
    
  4. [Conditional] - 条件编译
    控制方法的调用是否生效(如调试时保留日志)。

    #define DEBUG // 定义编译符号
    
    public class Logger
    {
        [Conditional("DEBUG")]
        public static void Log(string message)
        {
            Console.WriteLine(message);
        }
    }
    // 调用:仅在 DEBUG 定义时生效
    Logger.Log("Debug mode!");
    

三、自定义特性

你可以通过继承 Attribute 类定义自己的特性。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class AuthorAttribute : Attribute
{
    public string Name { get; }
    public DateTime Date { get; set; }

    public AuthorAttribute(string name)
    {
        Name = name;
    }
}

[AttributeUsage]:指定特性的作用目标(类、方法等)和规则。
AttributeTargets:指定应用目标(如 Class, Method, Property 等)。
AllowMultiple:是否允许多次应用同一特性。
Inherited:是否允许派生类继承该特性。

[Author("Alice", Date = "2025-01-01")]
[Author("Bob", Date = "2025-02-01")] // AllowMultiple = true 时允许多次应用
public class MyClass
{
    [Author("Charlie")]
    public void MyMethod()
    {

	}
}

四、通过反射读取特性

特性本身的逻辑需要通过反射来实现。
示例:读取类的 AuthorAttribute

Type type = typeof(MyClass);
var attributes = type.GetCustomAttributes(typeof(AuthorAttribute), false);

foreach (AuthorAttribute author in attributes)
{
    Console.WriteLine($"作者:{author.Name},日期:{author.Date}");
}

输出:

作者:Alice,日期:2025-01-01
作者:Bob,日期:2025-02-01

五、实际应用场景

  1. 数据验证

    使用特性标记属性的验证规则(如字符串长度、数值范围)。

    using System.ComponentModel.DataAnnotations;
    public class user
        {
            [Required(ErrorMessage="用户名不为空")]
            [MaxLength(20)]
            public String Name { get; set; }
        }
    
  2. Web API 路由配置
    在 ASP.NET Core 中用 [Route] 和 [HttpGet] 标记路由。

[Route("api/[controller]")]
public class UserController : Controller
{
    [HttpGet("{id}")]
    public IActionResult GetUser(int id)
    {
    }
}

  1. ORM 映射
    使用特性标记类与数据库表的映射关系
[Table("Users")]
public class User
{
    [Key]
    [Column("UserId")]
    public int Id { get; set; }
}

六、练习

定义一个 [Range] 特性,用于限制属性的数值范围。

    [AttributeUsage(AttributeTargets.Property)]
    public class RangeAttribute : Attribute
    {
        public int Max { get; }
        public int Min { get; }
        public string ErrorMessage { get; set; }

        public RangeAttribute(int min,int max)
        {
            Min = min;
            Max = max;
            ErrorMessage = $"数值必须在{Min}{Max}之间";
        }
    }


	public class User
	{
	    [Range(1, 120, ErrorMessage = "年龄必须在 1 到 120 之间。")]
	    public int Age { get; set; }
	}

你可能感兴趣的:(上位机,上位机,c语言)