C#创建一个不可为空的字符串.是否有可能?不知何故? [英] C# creating a non-nullable string. Is it possible? Somehow?
问题描述
所以您不能继承string
.您不能创建不可为空的string
.但是我想这样做.我想要一个类,我们将其称为nString,否则它将为null时将返回默认值.我有可能知道谁有多少个空字符串甚至什至空对象的JSON对象.我想创建具有永远不会返回null的字符串的结构.
So you can't inherit string
. You can't make a non-nullable string
. But I want to do this. I want a class, let's call it nString that returns a default value when it would otherwise be null. I have JSON objects that might have who knows how many null strings, or even null objects. I want to create structs that have strings that will never return null.
public struct Struct
{
public nString value;
public nString value2;
}
我想我可以做这样的事情:
I suppose I could do something like this:
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; } };
}
但是还有很多工作要做.有什么办法吗?
But that's so much more work. Is there any way to do this?
推荐答案
您当然可以具有以下nString
结构:
You could of course have the following nString
struct:
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";
这将允许从string
进行投射.在幕后,它执行与示例相同的转换,您不必为每个属性都键入它.我确实想知道这对您的应用程序的可维护性有什么影响.
This would allow casting from and to string
. Under the hood it performs the same cast as your example, you just don't have to type it out for every property. I do wonder what this does to maintainability for your application though.
这篇关于C#创建一个不可为空的字符串.是否有可能?不知何故?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!