如何通过名称从类中获取System.Nullable的默认类型?

时间:2017-07-19 07:49:59

标签: c# class types casting

所以,我很难从int转换System.Nullables。

经过一些研究后我修改了我的代码,但我不知道如何通过名字从我的班级中获取类型。

        for (int i = 0; i < m_textEdits.Count; i++)
        {
            string fieldName = m_textEdits[i].Name.Substring(m_textEdits[i].Name.LastIndexOf("_") + 1);
            System.Reflection.PropertyInfo propInfo = m_aktuelleZeille.GetType().GetProperty(fieldName);
            if (propInfo != null)
            {
                if (propInfo.GetMethod.ToString().Contains("Null"))
                {
                    propInfo.SetValue(m_aktuelleZeille, m_textEdits[i].EditValue ?? default( IDK WHAT TO PUT IN HERE ));
                }
                else if (propInfo.SetMethod != null) propInfo.SetValue(m_aktuelleZeille, m_textEdits[i].EditValue);
            }
        }

m_texedits是Textedits列表,Textedit被称为例如“tb_Menge”,因此在fieldname中代表“Menge”,m_aktuelleZeille是我的类,其中包含例如:

    private int? menge;
    public int? Menge
    {
        get { return menge; }
        set
        {
            if (value != menge)
            {
                menge = value;
                OnPropertyChanged("Menge");
            }
        }
    }

其他如果工作正常,就好像我得到可以为空的类型(这就是为什么我实现了if)

1 个答案:

答案 0 :(得分:1)

我不确定你究竟在问什么,但我认为你正在寻找底层类型的默认值。例如如果int?则默认为int,即0?

如果是这种情况,那么您可以在PropertyInfo对象上使用GenericTypeArguments,它将为您提供Nullable<T>的通用参数,然后您可以使用它来获取默认值。

E.g。 var defaultValue = Activator.CreateInstance(propInfo.GenericTypeArguments.First());

但是,我会谨慎使用Nullable<T>的默认值为null,而不是基础值的默认值。有关详情,请参阅What is the default value of the nullable type "int?" (including question mark)?