C# Type suffix for decimal

2019-03-22 15:37发布

I don't know what the correct wording is for what I am trying to achieve so it may already be posted online. Please be kind if it is.

Ok so basically I have this method.

public static T IsNull<T>(IDataReader dr, String name, T nullValue)
{
    return Helpers.IsNull(dr, dr.GetOrdinal(name), nullValue);
}

public static T IsNull<T>(IDataReader dr, Int32 index, T nullValue)
{
    if (dr.IsDBNull(index))
    {
        return nullValue;
    }
    else
    {
        return (T)dr.GetValue(index);
    }
}

Being called as Helpers.IsNull(dr, "UnitWholeSale", 0d) and the error I am getting is "Cannot convert from double to decimal".

Now I know I can use decimal.Zero but is there some way that I can simply go 0dec or something similar? I just hate those long shortcut values (especially when you are calling a constructor with 20 parameters).

7条回答
Evening l夕情丶
2楼-- · 2019-03-22 15:41
float value = 0f || 0.0f || (float)0;
double value = 0d || 0.0d || (double)0;
decimal value = 0m || 0.0m || (decimal)0;

Be aware that each last example is a cast and therefor can lose precision

查看更多
霸刀☆藐视天下
3楼-- · 2019-03-22 15:41

M is the suffix for decimal values, e.g. 200.32M is considered to be of type decimal to the compiler.

查看更多
来,给爷笑一个
4楼-- · 2019-03-22 15:43

0m will give you a decimal 0 value.

For the sake of completeness,

0.0 - double
0f  - float
0m  - decimal
查看更多
来,给爷笑一个
5楼-- · 2019-03-22 15:53

I assume nullValue is really defaultvalue, otherwise you could just do

public static T IsNull<T>(IDataReader dr, Int32 index)
{
    if (dr.IsDBNull(index))
    {
        return default(T);
    }
    else
    {
        return (T)dr.GetValue(index);
    }
}

Also looking more closely at your method you probably want a convertible value and use Convert.ChangeType() , I don't think the simple casting would work for all types:

public static T IsNull<T>(IDataReader dr, Int32 index) where T: IConvertible 
{
    if (dr.IsDBNull(index))
    {
        return default(T);
    }
    else
    {
        return (T)Convert.ChangeType(dr.GetValue(index), typeof(T));
    }
}
查看更多
家丑人穷心不美
6楼-- · 2019-03-22 15:56

Use 0.0m instead - m denotes decimal.

查看更多
走好不送
7楼-- · 2019-03-22 16:02

0m is how you say (decimal)0 because m is the suffix that means decimal.

Other suffixes are f for float, d for double, u for unsigned, and l for long. They can be either upper- or lower-case and u can be combined with l in either order to make a ulong.

Although the suffixes are not case-sensitive, keep in mind what it says in the C# language specification, section 2.4.4.2:

As a matter of style, it is suggested that “L” be used instead of “l” when writing literals of type long, since it is easy to confuse the letter “l” with the digit “1”.

查看更多
登录 后发表回答