允许public / empty值为public数据类型

时间:2012-11-27 14:34:11

标签: c# parsing null

通过Web表单上传文件并将其内容解析为列表在解析C.MN,C.LN,C.Val时如何允许null或空值这三个是声明为这样的公共数据类型

Namespace datatypes

       Public class Uploads
  {

        Public long Mn  {get; set;}
        Public int LN     { get;set    }
         Public int Val    {Get;Set}
    }

  List<Uploads> CDU = new List<Uploads>();
                string[] fields;

                string data = read.ReadLine();
                while ((data = read.ReadLine()) != null)
                {
                    if (data.Length != 0)
                    {
                        Uploads C = new Uploads();
                        fields = data.Split(',');
                        C.LN = Convert.ToInt32(fields[0]);
                        C.MN = Convert.ToInt64(fields[1]);                           
                        C.Val = Convert.ToInt32(fields[2]);
                        CDU.Add(C);

2 个答案:

答案 0 :(得分:2)

简而言之,您必须使用可空值类型,例如

public class Uploads
{
    public long? Mn { get; set; }
    public int? LN { get; set; }
    public int? Val { get; set; }
}

当然,你需要弄清楚是给它们一个值还是留空,大概是根据字符串是否为空。

例如:

C.LN = fields[0] == "" ? (int?) null : Convert.ToInt32(fields[0]);

或者只是:

if (fields[0] != "")
{
    C.LN = Convert.ToInt32(fields[0]);
}

顺便说一句,这些名字完全不可维护。在六个月内,你会知道他们的意思吗?

答案 1 :(得分:1)

使用像这样的可空类型:

public class Uploads
{
    public long? Mn { get; set; }
    public int? LN { get; set }
    public int? Val { get; set }
}

有关将字符串解析为可空值的信息,请参阅here