我试图访问数据:

1   DrugName    Paracetamolum   Coffeinum   NULL    NULL

有田野..

id-ProductName -Substance1...

这是模型:

namespace Pharma;


public partial class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string Substance1 { get; set; }
    public string Substance2 { get; set; }
    public string Substance3 { get; set; }
    public string Substance4 { get; set; }



    // constructor
    public Product()
    {
        // ProductName ??= "";
        // Substance1 ??= "";
        // Substance2 ??= "";
        // Substance3 ??= "";
        // Substance4 ??= "";

        if (ProductName == null)
        {
            ProductName = "";
        }
        if (Substance1 == null)
        {
            Substance1 = "";
        }
        if (Substance2 == null)
        {
            Substance2 = "";
        }
        if (Substance3 == null)
        {
            Substance3 = "";
        }
        if (Substance4 == null)
        {
            Substance4 = "";
        }
    }
}

我有Data is Null个错误. 然后我修改了字段:

   public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string? Substance1 { get; set; }
    public string? Substance2 { get; set; }
    public string? Substance3 { get; set; }
    public string? Substance4 { get; set; }

通过添加"?"然后它就起作用了. 但如果不起作用,为什么这不起作用:

if (Substance4 == null)
            {
                Substance4 = "";
            }

我试图理解.Net的工作方式,我有一个问题. 为什么添加"?"有效,但如果声明不起作用呢?

推荐答案

问号(?)在您的财产中表明它是可撤销的.意思是:- It defaults to NULL value,并且在构造函数运行之前,属性现在用空初始化.

在C#等编程语言中(遵循严格的方法),是为了确保代码中的编译时间和运行时错误更少.You must initialize a property/variable before you use it.在早期的情况下,您声明了属性,但没有分配值.当您使用(?)时,它默认为空值,这是C#中的有效值.

Csharp相关问答推荐

EF Core的GbContent如何 suppress 所有CS 8618(不可为空属性)警告?

PostingAsJsonAschange在从调用的方法返回时给出500错误

Plotly.NET访问互联网时出现异常

为什么我不能更改尚未设置的模拟对象属性的值?

处理. netstandard2.0项目中HttpClient.SslProtocol的PlatformNotSupportedException问题""

WPF Windows初始化正在锁定. Net 8中分离的线程

为什么我的ASP.NET核心MVC应用程序要为HTML元素添加一些标识符?

如何注销Microsoft帐户?

在一个模拟上设置一个方法,该模拟具有一个参数,该参数是一个numc函数表达式

有没有办法在WPF文本框中添加复制事件的处理程序?

创建临时Collection 最有效的方法是什么?堆栈分配和集合表达式之间的区别?

如何在C#中从正则表达式中匹配一些数字但排除一些常量(也是数字)

.NET SDK包中的官方C#编译器在哪里?

如何在C#中创建VS代码中的控制台应用程序时自动生成Main方法

为什么方法的值在SELECT方法中不会更改?

C#多键字典和TryGetValue

.NET 8在appsettings.json中核心使用词典URI、URI&>

Content WithTargetPath实际上是有效的MSBuild项吗?

C#中COM对象的实际地址

如何将行添加到DataGrid以立即显示它?