admin管理员组

文章数量:1200985

Context:

I have a 8 console app and I have a poco mapped to a section of the appsetting.json file.

Code to deserialize the appsetting.json AppSettings section to the Poco:

_settings = _configuration.GetRequiredSection("AppSettings").Get<AppSettings>();

AppSettings:

 public class AppSettings
  {
    public List<PipeCfg> Pipes { get; set; }
  }

PipeCfg:

public class PipeCfg {
....
      public const string DefaultFileNamePattern = "^.+$";
      private string[] _fileNamePatterns;
      private static readonly string[] DefaultFileNamePatterns = new [] {DefaultFileNamePattern};
      public string[] FileNamePatterns
      {
        get =>  _fileNamePatterns == null || _fileNamePatterns.Length == 0 ? DefaultFileNamePatterns: _fileNamePatterns;
        set
        {
          // Here I logged the value that is passed to the function
          string valueAsStr = 
            value switch 
            {
              null => "NULL",
              [] => "Empty",
              _ => String.Join(", ", value)
            }
            ;
          _log.Info($"FileNamePatterns({Id}) -> {valueAsStr}");
          _fileNamePatterns = value;
        }
      }
.....

appsettings.json:

{
  ....
  "AppSettings": {
    "Pipes": [
      {
        ....
        "FileNamePatterns": ["^.*\\.txt$"]
      }
    ],
    ...

FileNamePatterns is a new property I added to the PipeCfg existing class, and my thought was to initialize the FileNamePatterns array to a default value in case it is not specified in the appsettings.json file. This is to keep the app backwards compatible with the existing appsettings.json file.

Issue:

The value that is assigned to FileNamePatterns is actually: ["^.+$", "^.*\\.txt$"] instead of ["^.*\\.txt$"] which I found surprising. If I don't assign the default value and have simply public string[] FileNamePatterns {get; set;} it works as expected, of course.

Any idea why the api is doing this?

TIA

本文标签: