简体   繁体   English

可以为空还是默认值?

[英]Nullable or default value?

What class should I use? 我应该使用什么课程?

public class Category
{
    public int Id {get;set;}
    public int IdParent {get;set;}
    public string Title {get;set;}
}
or
public class Category
{
    public int Id {get;set;}
    public Nullable<int> IdParent {get;set;}
    public string Title {get;set;}
}

Take into account that auto increment starts from 1 and category can be without parent category. 考虑到自动递增从1开始,并且类别可以没有父类别。

If it can be without a parent, you want nullable. 如果可以没有父母,则希望为空。

To make your code more readable, you can do: 为了使代码更具可读性,您可以执行以下操作:

public class Category
{
    public int Id {get;set;}
    public int? IdParent {get;set;}
    public string Title {get;set;}
}

(Edit: Also, the class declaration shouldn't have parens) (编辑:此外,类声明不应有括号)

The Nullable<int> conveys the intent much better than the use of a default value, so I would definitely use it instead of checking for zero. Nullable<int>传达的意图比使用默认值要好得多,因此我肯定会使用它而不是检查零。 It also makes the check for nullness required, whereas if you are using a default value you may forget to do the check. 它还会要求检查是否为空,而如果使用默认值,则可能会忘记进行检查。

In case you do decide to go with zero as a "no parent", you should define a named constant for it: 如果您确实决定使用零作为“无父”,则应为其定义一个命名常量:

public class Category
{
    public const int NoParent = 0;
    public int Id {get;set;}
    public int IdParent {get;set;}
    public string Title {get;set;}
}

I'm not sure what you're trying to do, but if you want to use this to insert with auto increments you probably want your id to be nullable too. 我不确定您要做什么,但是如果您想使用此值以自动增量插入,您可能还希望ID也可以为空。

public class Category
{
    public int? Id { get; set; }
    public int? IdParent { get; set; }
    public string Title { get; set; }
}

I would use the second option, because it better communicates the fact that a category can have no parent. 我将使用第二个选项,因为它可以更好地传达类别可以没有父项的事实。 With the first option, you need to use a magic value to indicate a missing parent. 对于第一个选项,您需要使用魔术值来指示缺少的父对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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