如何使我的字符串属性可以为空?

问题描述 投票:31回答:7

我想让人的中间名可选。我一直在使用C#.net代码的第一种方法。对于整数数据类型,只需使用?运算符使其可以为空即可。我正在寻找一种让我的sting变量可以为空的方法。我试图搜索但找不到让它可以为空的方法。

以下是我的代码。请建议我如何让它可以为空。

public class ChildrenInfo
{
    [Key]
    public int ChidrenID { get; set; }

    [Required]
    [Display(Name ="First Name")]
    [StringLength(50,ErrorMessage ="First Name cannot exceed more than 50 characters")]
    [RegularExpression(@"^[A-Z]+[a-z]*$",ErrorMessage ="Name cannot have special character,numbers or space")]
    [Column("FName")]
    public string CFName { get; set; }

    [Display(Name ="Middle Name")]
    [RegularExpression(@"^[A-Z]+[a-z]*$",ErrorMessage ="Middle Name cannot have special character,numbers or space")]
    [StringLength(35,ErrorMessage ="Middle Name cannot have more than 35 characters")]
    [Column("MName")]
    public string? CMName { get; set; }
}   
c# asp.net-mvc entity-framework ef-migrations
7个回答
97
投票

String是一个引用类型,并且始终可以为空,您不需要做任何特殊操作。只有值类型才需要指定类型可为空。


8
投票

System.String是一个引用类型,因此您不需要执行任何操作

Nullable<string>

它已经有一个空值(空引用):

string x = null; // No problems here

5
投票

无论如何,字符串在C#中都可以为空,因为它们是引用类型。你可以使用public string CMName { get; set; },你就可以将它设置为null。


1
投票

正如其他人所指出的那样,字符串在C#中总是可以为空的。我怀疑你是在问这个问题,因为你不能把中间名留空或空白?我怀疑问题在于验证属性,很可能是RegEx。我无法在脑海中完全解析RegEx,但我认为你的RegEx坚持第一个角色出现。我错了 - RegEx很难。在任何情况下,尝试注释掉您的验证属性并查看它是否有效,然后一次一个地添加它们。


0
投票

无法使引用类型为Nullable。只有值类型可以在Nullable结构中使用。将问号添加到值类型名称使其可为空。这两行是相同的:

int? a = null;
Nullable<int> a = null;

0
投票

您不需要做任何事情,modelbinding会将null传递给变量而不会出现问题。


0
投票

string类型是引用类型,因此默认情况下它可以为空。您只能将Nullable<T>与值类型一起使用。

public struct Nullable<T> where T : struct

这意味着无论为泛型参数替换何种类型,它都必须是值类型。


0
投票

在qazxsw poi发布之后,您可以引用类型以使其可以为空。为此你必须添加

c# 8.0

命名空间的功能。这是详细的#nullable enable

例如这样的东西会起作用:

here

您还可以看看John Skeet的#nullable enable namespace TestCSharpEight { public class Developer { public string FullName { get; set; } public string UserName { get; set; } public Developer(string fullName) { FullName = fullName; UserName = null; } }} ,它解释了细节。

© www.soinside.com 2019 - 2024. All rights reserved.