简体   繁体   中英

how to get the anonymous backing field name of an auto-implemented properties

Not a full expert in C# here. Sorry in advance if this is a very common question.

consider the following property.

public bool IsOn{ get;set; }

above getter/setter property has anonymous backing field according to https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

Is there a way for me to see what this "anonymous backing field" name is so that I can expand the setter without adding extra code. All I want to do is log the content of the values that's getting set to in a dll where this code exist. For example,

public bool IsOn
{ 
   get;
   set
   {
      Log(value);
      "field name generated by c#" = value;
   }
}

Or do I have to create a field manually every time I want to see what the value is being set to? if so it seems like a very unproductive approach to have them used when we consider about usability. Mind you this is only one of the setters I want to log out. there are many more needs logging on this specific dll

An Auto-Implemented Property is a property that has the default get- and set-accessors. If you have to add logic to them, you have to create a usual property with a backing field:

private bool _IsOn;

public bool IsOn
{ 
   get { return _IsOn; }
   set
   {
      Log(value);
      _IsOn = value;
   }
}

However, a property that is logging somewhere is not a real property anymore, that's a heavy side-effect in my opinion. I would make it a method:

private bool _isActive = false;

public void ChangeState(bool active)
{
      Log(active);
    _isActive = active;
}

public bool IsActivated => _isActive;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM