C# 3.0 有没有更好的方法在C#3.0中编写这行C#代码?
我的财产声明如下:C# 3.0 有没有更好的方法在C#3.0中编写这行C#代码?,c#-3.0,properties,nullable,C# 3.0,Properties,Nullable,我的财产声明如下: public decimal? MyProperty { get; set; } MyProperty == null ? null : MyProperty.ToString() 我需要将此值作为字符串传递给另一个方法,因此我看到的唯一方法如下所示: public decimal? MyProperty { get; set; } MyProperty == null ? null : MyProperty.ToString() 当有许多类似的属性被传递到一个方法中
public decimal? MyProperty { get; set; }
MyProperty == null ? null : MyProperty.ToString()
我需要将此值作为字符串传递给另一个方法,因此我看到的唯一方法如下所示:
public decimal? MyProperty { get; set; }
MyProperty == null ? null : MyProperty.ToString()
当有许多类似的属性被传递到一个方法中时,这看起来非常混乱
有人知道有没有更好更简洁的方法来写这篇文章吗
哦,如果有人能为这个问题想出一个更合适的标题,请随意更改…您可以使用HasValue而不是比较:
MyProperty.HasValue ? MyProperty.Value.ToString() : null;
您可以使用
null.ToString()
让string在包含属性的类上获取属性,这样就不会很混乱,因为您需要获取字符串版本
public decimal? MyProperty { get; set; }
public string MyPropertyString
{
get
{
return MyProperty.HasValue ? MyProperty.Value.ToString() : null;
}
}
您可以在Decimal上声明扩展方法
public static string Str(this decimal? value)
{
return value == null ? null : MyProperty.ToString()
}
你可以这样称呼它:
MyProperty.Str()
如果允许零istead为null,则:
(MyProperty ?? 0).ToString()
否则,添加扩展方法:
public static string AsString(this decimal? val)
{
return val == null ? null : val.Value.ToString();
}
// Use:
MyProperty.AsString() // This will NEVER cause NullReferenceException
哇,真的吗?我学到了一些新东西。我从来没有试过那样做,以为它会抛出一个空指针异常哇!我不知道。ToString仍然适用于一个可为null的值。太棒了!。。。但是如果值为NULL,听起来作者想要NULL@Dmitry:null==“”用于中的字符串。NET@Cameron,我相信它(null!=“”)在.NET中。在代码中检查它。这就是为什么我们在.NET2.0.No中得到string.IsNullOrEmpty方法。应为十进制**?**(可为空)