Is there a better way to write this line of C# code in C#3.0?

与世无争的帅哥 提交于 2019-12-05 00:25:48

问题


I have a property declared as follows:

public decimal? MyProperty { get; set; }

I am needing to pass this value to another method as a string and so the only way I see to do so is as follows:

MyProperty == null ? null : MyProperty.ToString()

This looks very messy when you have a number of similar properties being passed into a method.

Does anyone know if there is a better and more concise way of writing this?

Oh, and if anyone can think of a more appropriate title to this question please feel free to change it...


回答1:


You can use the Nullable<T>.ToString() override ...

var s = MyProperty.ToString(); // returns "" if MyProperty is null



回答2:


You could use HasValue instead of the comparison:

MyProperty.HasValue ? MyProperty.Value.ToString() : null;



回答3:


Make string get properties on the class containing the property and it won't be messy wen you need to get the string version.

    public decimal? MyProperty { get; set; }

    public string MyPropertyString
    {
        get
        {
            return MyProperty.HasValue ? MyProperty.Value.ToString() : null;
        }
    }



回答4:


If it is ok to have zero istead of null then:

(MyProperty ?? 0).ToString()

Otherwise add extension method:

public static string AsString(this decimal? val)
{
    return val == null ? null : val.Value.ToString();
}

// Use:
MyProperty.AsString() // This will NEVER cause NullReferenceException



回答5:


You could declare an extension method on Decimal.

public static string Str(this decimal? value)
{
    return value == null ? null : MyProperty.ToString()
}

You then call it like this:

MyProperty.Str()


来源:https://stackoverflow.com/questions/1242883/is-there-a-better-way-to-write-this-line-of-c-sharp-code-in-c3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!