如何在一个类中初始化非空字符串?

时间:2019-12-02 09:05:14

标签: c# string initialization non-nullable

我有这个项目:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
  </ItemGroup>
</Project>

这是主要课程:

namespace CSharp8
{
    using System;
    using Microsoft.Extensions.Configuration;

    internal class Program
    {
        private static void Main()
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", false, true)
                .Build();
            var appSettings = configuration.Get<AppSettings>();
        }

        public class AppSettings
        {
            public string SourceServer { get; set; }
            public string TargetServer { get; set; }
        }
    }
}

这是appsettings.json:

{
  "SourceServer": "prodtools",
  "TargetServer": "qatools"
}

在AppSettings的属性上,我收到此警告:

  

警告CS8618不可初始化的属性'SourceServer'未初始化。   考虑将属性声明为可为空。

我可以用不同的方式修复它。

1。

public class AppSettings
{
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
    public string SourceServer { get; set; }
    public string TargetServer { get; set; }
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
}

我不喜欢这样,因为我认为规则在整个项目中必须一致。

2。

public class AppSettings
{
    public string SourceServer { get; set; } = "";
    public string TargetServer { get; set; } = "";
}

我不喜欢这样,因为空字符串是错误的值。这些属性似乎已初始化,但是这些值没有意义,如果我无法正确初始化它们,它们将破坏我的程序。

3。

public class AppSettings
{
    public string SourceServer { get; set; } = null!;
    public string TargetServer { get; set; } = null!;
}

这很有意义,实例是用空值创建的,并且这些值会立即初始化。但是我不确定这些代码将来是否会破解,因为这些属性不可为空。

4。

public class AppSettings
{
    public string? SourceServer { get; set; }
    public string? TargetServer { get; set; }
}

这也很有意义。在微秒内,属性将保持为空。但是在我的程序中,它们必须具有价值。所以我也不喜欢。

您认为哪种风水最多?还有其他建议吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

在这种情况下,我倾向于使用以下内容,但我想这是偏爱的问题:

Public class AppSettings
{
  public string SourceServer{ get; private;} = string.Empty();
  public string TargetServer{ get; private;} = string.Empty();
}

然后在使用任何一个值之前,请检查它们的值。像

var settings = new AppSettings();
if(string.IsNullOrWhitespace(settings.SourceServer)) 
{
 // Some error handling code
 return;
}

//process SourceServer value

我想您还是应该在存储或使用它之前验证该值,所以这不是问题。