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
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!
}
}
}