【问题标题】:Recursive call to generic function with DataRow parameter - MakeGenericMethod Fails使用 DataRow 参数递归调用泛型函数 - MakeGenericMethod 失败
【发布时间】:2011-10-08 13:40:07
【问题描述】:

问题是:如果我有 MyConvertDataRowToEntity(DataRow row ) 我用 Parent 类型的 T 对象调用,在里面我用子类型 Child 调用相同的函数我应该如何传递 DataRow 参数? 调用 MakeGenericMethod 的 Invoke 时会产生问题。 确实将类型更改为 DataSet 、 string 和 String 类型。 没有运气。 (我认识列名中的子对象 bu 前缀 - PrefixDataColumn)

public static T MyConvertDataRowToEntity<T>(DataRow row ) where T : class, new()
    {

        Type objType = typeof(T);
        Type parentObjType = typeof(T);
        T obj = Activator.CreateInstance<T>(); //hence the new() contsraint
        PropertyInfo propertyGenericType = null;
        object childInstance = null;
        PropertyInfo property;
        string childColumnName = string.Empty ;
        foreach (DataColumn column in row.Table.Columns)
        {
            column.ColumnName = column.ColumnName.Replace("_", "");

            string PrefixDataColumn;
            if (column.ColumnName.IndexOf(".") > (-1))
            {
                ///gets the prefix that is the same as child entity name
                PrefixDataColumn = column.ColumnName.Substring(0, column.ColumnName.IndexOf("."));
                ///the column name in the child
                int length = column.ColumnName.Length - 1;
                int start = column.ColumnName.IndexOf(".") + 1;
                childColumnName = column.ColumnName.Substring(column.ColumnName.IndexOf(".") + 1);
                propertyGenericType = objType.GetProperty(PrefixDataColumn,
                                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
                parentObjType = objType;
                if (propertyGenericType != null)
                {
                    Type childType = propertyGenericType.PropertyType;
                    objType = childType;
                    childInstance = Activator.CreateInstance(propertyGenericType.PropertyType);


                    // get the get method for the property
                    MethodInfo method = propertyGenericType.GetGetMethod(true);
                    // get the generic get-method generator 
                    MethodInfo genericHelper = typeof(DataUtil).GetMethod("MyConvertDataRowToEntity", BindingFlags.Public | BindingFlags.Static);

                    List<Type> signature = new List<Type>();
                    // first type parameter is type of target object
                    signature.Add(childType);

                    //next parameters are real types of method arguments
                    foreach (ParameterInfo pi in genericHelper.GetParameters())
                    {
                        signature.Add(pi.ParameterType);
                    }

                    // last parameters are known types of method arguments
                    signature.AddRange(typeof(T).GetGenericArguments());

                    // reflection call to the generic get-method generator to generate the type arguments
                    //MethodInfo constructedHelper = genericHelper.MakeGenericMethod(signature.ToArray());

                    // reflection call to the generic get-method generator to generate the type arguments
                    MethodInfo constructedHelper = genericHelper.MakeGenericMethod(childType );

                    // now call it. The null argument is because it's a static method.
                    object ret = constructedHelper.Invoke(null, new object[] { method });

                   // object myObj =  method.Invoke(null, row);
                   //// property.SetValue(obj, MyConvertDataRowToEntity<childInstance>(DataRow row),null);
                   // childInstance = DataUtil.GetMethod("MyConvertDataRowToEntity").MakeGenericMethod(childType); //MyConvertDataRowToEntity<object>(row); 

                    //childType initializedChild = ;
                    //property.SetValue(obj, value, null);
                    //objType = parentObjType;
                }
                else
                {
                    continue; 
                }
            }


        }
        return obj;
    }

收到此错误: “System.Reflection.RuntimeMethodInfo”类型的对象无法转换为“System.Data.DataRow”类型。

有什么解决办法吗?

附言 尽可能缩小代码范围。

我怎样才能递归地调用带有除味剂类型的方法并传递数据行?

【问题讨论】:

  • 所以没有调试器来检查冗长的代码。请将其缩小到问题区域。更多文字将有助于您实现目标。
  • 一个简短但完整的程序来演示这个问题真的很有帮助。请阅读tinyurl.com/so-hints
  • 问题是:如果我有 MyConvertDataRowToEntity(DataRow row ) 并且我使用 Parent 类型的 T 对象调用并且在内部调用具有子类型 Child 的相同函数我应该如何传递 DataRow范围 ?调用 MakeGenericMethod 的 Invoke 时会产生问题。确实将类型更改为 DataSet 、 string 和 String 类型。没有运气。
  • 缩小了代码范围。

标签: c# generics recursion datarow


【解决方案1】:

错误的原因是因为您调用MyConvertDataRowToEntity&lt;ChildType&gt;,但随后将属性的getaccessor方法信息作为参数而不是仅包含这些字段的数据行传递。

如果您想继续使用当前使用的代码处理逻辑,您需要构建一个新的数据行,其中包含从列名开头删除的所需字段(带有前缀和“.”)。

或者,您可以创建一个辅助方法来接受列名、源对象并简单地更新值。

static void UpdateItemProperty<T>(T item, string columnName, object rowValue) {
  var prefixColumn=columnName.IndexOf(".")==-1 ? columnName : columnName.Split(".")[0];
  var pi = typeof(T).GetProperty(prefixColumn // Add your binding flags);
  // if pi==null then there is an error...
  if (column.ColumnName.IndexOf(".") == (-1)) { // No Nesting
    pi.SetValue(item,rowValue);
    return;
  }
  // Nesting 
  var child=pi.GetValue(item);
  if (child==null) {
        // Logic here to get childs type and create an instance then call pi.SetValue with child
  }
  var remainder=string.Join(',',columnName.Split(".").Skip(1).ToArray());
  // make your generic method info for UpdateItemProperty with pi.PropertyType into mi
  mi.Invoke(null,new object[] { child,remainder,value };
}

【讨论】:

  • 感谢您的回复。问题不是数据的修改,而是通过发送参数。我的意思是,当我使用 childType 调用该方法时,我无法发送该行。它失败并显示:“'System.Reflection.RuntimeMethodInfo' 无法转换为类型 'System.Data.DataRow'。”这就是麻烦!
  • 我的回应的重点是您的调用行将属性的方法信息作为参数传递,而不是方法需要的数据行。是不是需要先调用get方法来获取返回值?
  • 您好!也许我不清楚我的问题。我有一个带有 children 的分层对象。当我在对象中遇到强类型的某些属性时,我想递归地对该属性执行 MyConvertDataRowToEntity 。我将尝试仅创建相关列的数据行并回复您。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多