简体   繁体   English

如何更好地从非可空类型初始化可空类型?

[英]How to better initialize nullable type from non-nullable?

My objects often has nullable types properties that used as SQL commands parameters. 我的对象通常具有用作SQL命令参数的可空类型属性。

I initialize them next way: 我用以下方式初始化它们:

public int? Amount
{
    get
    {
        int i;
        int? amount = null;
        if (Int32.TryParse(Request["amount"], out i))
        {
            amount = i;
        }
        return amount;
    }
}

command.Parameters.Add("@amount").Value = (object)this.Amount ?? DbNull.Value;

How can I rewrite such initialization code to make it shorter or faster ? 我怎么可以重写这样的初始化代码,使其更短或更快

Firstly, don't do that; 首先,不要那样做; you are silently dropping the fact that you can't parse the data! 您正在默默地放弃无法解析数据的事实! Better to throw an exception in this case, or handle expected scenarios ( null , for example). 在这种情况下,最好抛出一个异常,或者处理预期的情况(例如null )。

string val = Request["amount"];
return string.IsNullOrEmpty(val) ? (int?)null : (int?)int.Parse(val);

1) Shorter != faster. 1)更短的!=更快。 Important to note. 重要说明。

2) This will work just as well: 2)这将同样有效:

public int? Amount
{
    get
    {
        int i;
        if (Int32.TryParse(Request["amount"], out i))
        {
            return i;
        }
        return null;
    }
}

Unless your caller demands a Nullable<T> , I'd suggest using a type like: 除非您的呼叫者要求Nullable<T> ,否则我建议使用类似以下的类型:

struct MaybeValid<T>
{
    public bool IsValid;
    public T Value;
}

That would allow: 这将允许:

Public MaybeValid<int> Amount
{
    Amount.Value = Int32.TryParse(out Amount.IsValid);
}

With Int32 , the extra typecasting effort probably isn't too much of an issue, but with larger types, it could be more significant. 使用Int32 ,额外的类型转换工作可能不会成为太大的问题,但是对于较大的类型,它可能会更重要。

我喜欢重写Randolpho和Marc的代码:

return Int32.TryParse(Request["amount"], out i)) ? (int?)i : (int?)null;
public int? Amount
{
    get
    {
         try 
         {
               return Int.Parse(Request["amount"]);
         }
          catch (exception e) 
         { 
               return null;
         }
     }
{

Performance is not really going to change, but if you really want to optimize, then you need to think about what is most common, if the values are almost always valid ints, then my approach is likely best, if not then your approach is best. 性能并不会真正改变,但是如果您真的想优化,那么您需要考虑最常见的情况,如果值几乎总是有效的整数,那么我的方法可能是最好的,如果不是,那么您的方法是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM