【问题标题】:Setting values of an object's non-value members through reflection通过反射设置对象的非值成员的值
【发布时间】:2012-03-24 01:09:48
【问题描述】:

我正在尝试编写一个非常松散耦合的方法来将从数据库返回并存储在DataTable 中的值映射到自定义对象的属性。这适用于所有值类型属性,但我无法设置本身是主类属性的对象的属性。这是我目前所拥有的:

    protected void AssignDataRowToFields(DataRow data, object currentClass = null)
    {
        string strPrefix = currentClass == null ? string.Empty : currentClass.GetType().Name;
        currentClass = currentClass ?? this;

        PropertyInfo[] properties = currentClass.GetType().GetProperties();

        foreach (PropertyInfo pi in properties)
        {
            if (pi.PropertyType.IsValueType || typeof(string).IsAssignableFrom(pi.PropertyType))
            {
                if (typeof(string).IsAssignableFrom(pi.PropertyType))
                    pi.SetValue(this, data[strPrefix + pi.Name].ToString(), null);
                else if (typeof(int).IsAssignableFrom(pi.PropertyType))
                    pi.SetValue(this, int.Parse(data[strPrefix + pi.Name].ToString()), null);
            }
            else
                this.AssignDataRowToFields(data, pi.GetValue(currentClass, null));
        }
    }

我递归调用AssignDataRowToFields 的最后一个else 总是为pi.GetValue(currentClass, null) 返回null。我也试过pi.GetGetMethod().Invoke(currentClass, null),但这也返回null。任何帮助将不胜感激,谢谢!

编辑:这里讨论的所有属性都是表单的自动属性:

public ComplexType theProperty { get; private set; }

【问题讨论】:

  • 子对象是已经创建了还是需要先实例化?
  • 这发生在父对象的原始实例化过程中,因此子对象需要实例化和分配。

标签: c#-4.0 reflection recursion


【解决方案1】:

确保您的类构造函数首先创建子对象。

【讨论】:

    猜你喜欢
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多