当前位置: 首页 > news >正文

C# 特性 学习记录

        在C#中,特性(Attribute)是一种用于向代码元素(如类、方法、属性等)添加元数据的机制。特性本身不会直接影响代码的执行,但它们可以提供额外的信息,这些信息可以在运行时通过反射(Reflection)来读取和使用。

用法:

一、描述

using System;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class DescriptionAttribute : Attribute
{
    public string Description { get; set; }
    public DescriptionAttribute(string description)
    {
        Description = description;
    }
}
[DescriptionAttribute("描述特性") ]//Attribute允许省略
public class Test
{

}

public class Program
{
    public static void Main(string[] args)
    {
        Type type= typeof(Test);
        object[] attributes = type.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if(attributes.Length > 0)
        {
            DescriptionAttribute descriptionAttribute= (DescriptionAttribute)attributes[0];
            Console.WriteLine(descriptionAttribute.Description);//会输出文字:描述特性
        }
        Console.Read();
    }
}

二、标记过时方法

using System;
 
public class Program
{
    [Obsolete("该方法已过时")]
    public static void ObsoleteMethod()
    {

    }
    public static void Main(string[] args)
    {
        ObsoleteMethod();
        Console.Read();
    }
}

三、控制序列化

using System;
using System.IO;
using System.Xml.Serialization;

[Serializable]
public class Test
{
    public string field1 = "";
    [XmlIgnore]
    public string field2 = "";
}

public class Program
{
    public static void Main(string[] args)
    {
        Test test;
        Test testDeserializer;
        XmlSerializer serializer;
        StringWriter writer;
        StringReader reader;

        test = new Test();
        test.field1 = "field1";
        test.field2 = "field2";

        serializer = new XmlSerializer(typeof(Test));
        writer = new StringWriter(); 
        serializer.Serialize(writer, test);
        Console.WriteLine($"XML序列化结果:\n{writer}");

        reader = new StringReader(writer.ToString());
        testDeserializer = (Test)serializer.Deserialize(reader);
        Console.WriteLine($"XML反序列化结果:\nfield1:[{testDeserializer.field1}].field2:[{testDeserializer.field2}]" );
        Console.Read();
    }
}

四、自定义验证

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Property)]
public class RangeAttribute : Attribute
{
    public int Min { get; }
    public int Max { get; } 
    public RangeAttribute(int min, int max)
    {
        Min = min;
        Max = max;
    }   
}

public class Test
{
    [Range(114,514)]
    public int Property1 {  get; set; }

    public  Test(int property1)
    {
        Property1 = property1;
    }

    public bool ValidateProperty1()
    {
        MemberInfo property1 = typeof(Test).GetProperty("Property1");
        RangeAttribute rangeAttribute = (RangeAttribute)Attribute.GetCustomAttribute(property1, typeof(RangeAttribute));
        if (rangeAttribute != null)
        {
            return Property1 >= rangeAttribute.Min && Property1 <= rangeAttribute.Max;
        }
        else
        {
            return true;
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Test test1 = new Test(123);
        Test test2 = new Test(999);
        Console.WriteLine(test1.ValidateProperty1());
        Console.WriteLine(test2.ValidateProperty1());
        Console.Read();
    }
}

五、条件编译

#define Debug
using System;
using System.Diagnostics;

public class Program
{
    [Conditional("Debug")]
    public static void Log(string message)
    {
        Console.WriteLine(message);
    }

    public static void Main(string[] args)
    {
        Log("Debug已定义");
        Console.Read();
    }
}

注释掉#define Debug代码,则执行不会输出“Debug已定义”。

http://www.dtcms.com/a/17809.html

相关文章:

  • springboot023学生宿舍管理系统
  • 《LSTM与HMM:序列建模领域的双雄对决》
  • GPU的核心的时钟频率,使用什么命令查看和计算
  • 蓝桥杯 Java B 组之简单数学问题(素数判断、最大公约数)
  • 在anaconda环境中构建flask项目的exe文件
  • DrissionPage(实战)
  • GitHub 使用教程:从入门到进阶
  • 异构计算架构助力智能座舱实现高效低耗体验
  • PMTUD By UDP
  • RK3588开发板部署DeepSeek-R1-Distill-Qwen-1.5B的步骤及问题
  • OSI 参考模型和 TCP/IP 参考模型
  • AI技术+Xsens惯性捕捉技术:科技碰撞下的无限可能
  • 【网络测试】tmux工具常用指令
  • 单片机上SPI和IIC的区别
  • 动态建表并插入数据
  • 【uniapp-小程序】实现方法调用的全局tips弹窗
  • Centos搭建python环境
  • Python创建Excel的方式——提供4中方式可供参考
  • Python基础语法精要
  • flutter常见面试题(欢迎私信投稿——更新到10)
  • 19vue3实战-----菜单子树的展示
  • web集群(LVS-DR)
  • 动态规划两个数组的dp问题系列一>两个字符串的最小ASCII 删除和
  • 【c++刷题】leetcode 200. 岛屿数量
  • 生物发酵展与2025生物医药创新技术与应用发展论坛同期盛大举办
  • DeepSeek教unity------UI框架
  • 基于51单片机的4位电子密码锁proteus仿真
  • Ubuntu下载安装Docker-Desktop
  • latex二重闭合积分显示
  • UI-设计规范大小总结