Determine Calling Object Type in C#

前端 未结 11 842
灰色年华
灰色年华 2021-02-05 14:37

Regardless of whether or not this is a good idea, is it possible to implement an interface where the executing function is aware of the calling object\'s type?

c         


        
11条回答
  •  隐瞒了意图╮
    2021-02-05 14:49

    Starting with Visual Studio 2012 (.NET Framework 4.5) you can automatically pass caller information to a method by using caller attributes (VB and C#).

    public void TheCaller()
    {
        SomeMethod();
    }
    
    public void SomeMethod([CallerMemberName] string memberName = "")
    {
        Console.WriteLine(memberName); // ==> "TheCaller"
    }
    

    The caller attributes are in the System.Runtime.CompilerServices namespace.


    This is ideal for the implementation of INotifyPropertyChanged:

    private void OnPropertyChanged([CallerMemberName]string caller = null) {
         var handler = PropertyChanged;
         if (handler != null) {
            handler(this, new PropertyChangedEventArgs(caller));
         }
    }
    

    Example:

    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (value != _name) {
                _name = value;
                OnPropertyChanged(); // Call without the optional parameter!
            }
        }
    }
    

提交回复
热议问题