zoukankan      html  css  js  c++  java
  • 在 .NET 4.0 中使用 .NET 4.5 中新增的特性(CallerMemberNameAttribute/CallerFilePathAttribute/CallerLineNumberAttribute)

    介绍

    标题中所说的三个特性 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
        {
    
        }
    }

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

    本博客内容,如需转载请务必保留超链接。

    Contact Me:Mail此处省略好几个字...
  • 相关阅读:
    Codeforces Round #213 (Div. 2) B. The Fibonacci Segment
    关于求解不定方程的n(n-1)=2m(m-1)的解法的总结
    objective-c @()
    objective-c 条件运算符
    关于判断两个矩阵相交的一点想法
    二维几何常用运算
    《为ipad而设计 打造畅销APP》读书笔记
    ios cocos2d FPS过低的解决方法
    python 根据对象和方法名,返回提供这个方法的定义的类
    python 获取类的属性
  • 原文地址:https://www.cnblogs.com/jroger/p/4805410.html
Copyright © 2011-2022 走看看