在 .NET 4.0 中使用 .NET 4.5 中新增的特性(CallerMemberNameAttribute/CallerFilePathAttribute/CallerLineNumberAtt...

介绍

标题中所说的三个特性 CallerMemberNameAttribute / CallerFilePathAttribute / CallerLineNumberAttribute 我们统称为调用者信息特性,正常情况下在 .NET Framework 4.0 中是无法使用的。因为这三个特性是 .NET Framework 4.5 中新增的。然而这三个特性的作用只是请求编译器在编译过程中进行代码的转换。

使用示例

    static void Main( string[] args )
    {
        var productInfo = new ProductInfo();

        productInfo.Name = "lumia";

        productInfo.PropertyChanged();

        Console.ReadKey( true );
    }
}

public class ProductInfo
{
    private string _name;

    public string Name
    {
        get { return this._name; }
        set
        {
            this._name = value;
            this.PropertyChanged();
        }
    }

    public void PropertyChanged([CallerMemberName]string name = "", [CallerLineNumber]int line = 0, [CallerFilePath]string file = "")
    {
        Console.WriteLine("------------------------------------------------");
        Console.WriteLine($"Name : {name}, \nLine : {line}, \nPath : {file}");
    }
}

注意上面标为橘红色的语句。运行时将自动填充这三个可选参数的值。开发过 WPF 的同学都知道这是多么的方便,不用显示指定参数名称。然而入我上面所说他不能在 .NET Framework 4.0 中使用,不过还好有办法。很简单,我们只需要自己定义这三个特性就可以了,代码如下。

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public class CallerMemberNameAttribute : Attribute
    {

    }

    [AttributeUsage(AttributeTargets.Parameter, Inherited = false )]
    public class CallerFilePathAttribute : Attribute
    {

    }

    [AttributeUsage(AttributeTargets.Parameter, Inherited = false )]
    public class CallerLineNumberAttribute : Attribute
    {

    }
}

没有什么参数和成员在这三个特性里面。但要注意命名空间一定要与上面的一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值