C#中的特性

   C#中的特性,允许向程序的程序集增加元数据,用于保存程序结构信息。

1.Obsolete

    Obsolete特性标记方法已被弃用。并在代码编译时,显示警告信息。

[Obsolete("该方法已被弃用")]
static void OldMethod()
{
     Console.WriteLine("OldMethod");
}

2.Conditional

   Conditional特性,使用或取消方法的调用,执行依赖于指定的预处理标识符。

[Conditional("TEST")]
static void TestMethod()
{
    Console.WriteLine("TestMethod");
}

当在定义了#define TEST时,该方法被调用,否则不调用。一般用于调试信息的输出。

3.DebuggerStepThrough

   调试代码时,告诉调试器不要进入某些方法。当确定某些方法没有错误的时候,使用该特性。

[DebuggerStepThrough]
static void TestMethod2()
{
     Console.WriteLine("TestMethod2");
}

4.调用者信息特性

   CallerFilePath 获取调用该方法的文件路径
   CallerLineNumber 获取调用该方法的源文件的行号
   CallerMemberName 获取调用该方法的方法名

using System;
using System.Runtime.CompilerServices;

namespace CSharpTest
{
    class Program
    {
        //调用者信息特性
        static void PrintStr(string str, [CallerFilePath]string file = "", [CallerLineNumber]int line = 0,
            [CallerMemberName]string method = "")
        {
            Console.WriteLine(str);
            Console.WriteLine("文件名:" + file);
            Console.WriteLine("行号: " + line);
            Console.WriteLine("方法名: " + method);
        }

        static void Main(string[] args)
        {
            PrintStr("Hello,April");
            Console.ReadKey();
        }
    }
}

运行结果

5.自定义特性

   自定义特性类时,需要遵守一些规则:

  •    类名称以Attribute结尾
  •    继承System.Attribute
  •    一般情况下声明为sesealed,不能被继承
  •    表示目标结构的状态(包含字段及属性,一般不定义方法)   
using System;

namespace CSharpTest
{
    [Test("自定义特性类", 1.2)]
    class Program
    {
        [AttributeUsage(AttributeTargets.Class)] //该特性类适用范围
        sealed class TestAttribute : Attribute
        {
            public string Description { get; set; }
            public double Version { get; set; }

            public TestAttribute(string description, double version)
            {
                this.Description = description;
                this.Version = version;
            }
        }

        static void Main(string[] args)
        {
            Type type = typeof(Program);
            object[] array = type.GetCustomAttributes(false);
            TestAttribute attr = array[0] as TestAttribute;
            Console.WriteLine("Description: " + attr.Description);
            Console.WriteLine("Version: " + attr.Version);

            Console.ReadKey();
        }
    }
}

 运行结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值