【问题标题】:How get Default Type by System.Nullable from Class just by name?如何通过 System.Nullable 从类中仅按名称获取默认类型?
【发布时间】:2017-12-24 08:22:06
【问题描述】:

所以,我在转换 System.Nullables 时遇到了麻烦,比如 from int?。

经过一些研究,我修改了我的代码,但我不知道如何从我的类中仅通过 Name 来获取类型。

        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”,因此在字段名中代表“Menge”,m_aktuelleZeille 是我的类,其中包含示例:

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

else if 工作正常,只要我得到可为空的类型(这就是我实现 if 的原因)

【问题讨论】:

    标签: c# class types casting


    【解决方案1】:

    我不确定你到底在问什么,但我认为你正在寻找基础类型的默认值。例如if int? 则默认为 int,即 0?

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

    例如 var defaultValue = Activator.CreateInstance(propInfo.GenericTypeArguments.First());

    但是,我会谨慎使用 Nullable&lt;T&gt; 的默认值是 null,而不是基础值的默认值。有关更多信息,请参阅What is the default value of the nullable type "int?" (including question mark)?

    【讨论】:

    • propInfo.Generic ... 不起作用,我想将 m_textedits[i].editvalue 中的动态值投射到属性“Menge”上的我的类 m_aktuelleZeille 作为示例。问题是正常情况下,它与我的代码中的 else if 一起使用,但如果我的类中有属性,如 int?,它说我不能将 System.Decimal(Texedit 设置为数字)转换为 System.NullableInt32
    • 抱歉,我很难理解您要做什么。您能否更新问题以使其更清楚?
    猜你喜欢
    • 1970-01-01
    • 2010-11-19
    • 2011-04-07
    • 2017-04-14
    • 1970-01-01
    • 2013-08-20
    • 2013-11-29
    • 2011-12-11
    相关资源
    最近更新 更多