C#创建一个不可为空的字符串.可能吗?不知何故?

Jar*_*ice 11 c# string non-nullable

所以你不能继承string.你不能成为不可空的string.但我想这样做.我想要一个类,让我们称之为nString,否则返回默认值为null.我有JSON对象可能有谁知道有多少空字符串,甚至是空对象.我想创建具有永远不会返回null的字符串的结构.

public struct Struct
{
    public nString value;
    public nString value2;
}
Run Code Online (Sandbox Code Playgroud)

我想我可以这样做:

public struct Struct
{
    public string val { get { return val ?? "N/A"; } set { val = value; } }
    public string val2 { get { return val2 ?? "N/A"; } set { val2 = value; } };
}
Run Code Online (Sandbox Code Playgroud)

但那是更多的工作.有没有办法做到这一点?

C.E*_*uis 17

你当然可以有以下nString结构:

public struct nString
{
    public nString(string value)
        : this()
    {
        Value = value ?? "N/A";
    }

    public string Value
    {
        get;
        private set;
    }

    public static implicit operator nString(string value)
    {
        return new nString(value);
    }

    public static implicit operator string(nString value)
    {
        return value.Value;
    }
}

...

public nString val 
{ 
    get;
    set;
}

obj.val = null;
string x = obj.val; // <-- x will become "N/A";
Run Code Online (Sandbox Code Playgroud)

这将允许铸造和铸造string.在引擎盖下它执行与您的示例相同的演员表,您不必为每个属性键入它.我确实想知道这对您的应用程序的可维护性有何影响.

  • @valverij 我遵循的打字课程终于得到了回报! (2认同)
  • @t3dodson 我刚刚回答了这个问题,其中 OP 特别想要“一个默认值,否则它会为空”。也许您可以对这个问题发表评论,但请记住,它是在 2014 年提出的。 (2认同)