2014-12-01 2 views
0

이것은 2 시간이므로 이제는 확장 메서드에 대한 일부 반향을 만들려고합니다. 내가 원하는 것은 DataRow의 "필드"라는 일반 정적 메서드를 호출하고 성공하지 못했습니다. 아무도 도와 줄 수 있습니까?확장 메서드에 대한 반영

ParameterExpression pe = Expression.Parameter(typeof(DataRow), "field"); 
var x = typeof(DataRowExtensions).GetMethod(
    "Field", 
    new Type[]{typeof(DataRow),typeof(string)});        
var gx = x.MakeGenericMethod(typeof(DataRow)); 
var y = new[] { Expression.Constant(TwoParts[0]) }; 
Expression left = Expression.Call(pe, gx, y); 
Expression right = Expression.Constant(val.Remove(0, 1)); 
var w = e1 = Expression.NotEqual(left, right); 
+0

가능 중복 된 [I가 반사를 사용하여 확장 메서드를 호출하려면 어떻게합니까?] (http://stackoverflow.com/questions/1452261/how-do-i-invoke-an-extension-method-using- 반사) – pmcoltrane

+0

나는이 답변을 이미 보았지만, 나는 그것이 필요한 것과 일치하지 않는다. 사실, linq 함께 사용하려면 식 호출을 만들고 싶습니다. 정적 메서드를 독립적으로 호출하지 않습니다. – We0orad

답변

1

시도 :

Expression left = Expression.Call(null, gx, pe, Expression.Constant(TwoParts[0])); 

static 방법에 Expression.Call을 사용하여 첫 번째 매개 변수 null로 전달한다

여기 내 코드입니다. 인스턴스는 실제로 매개 변수입니다.

0

코드에서 Expression을 사용하는 이유가 확실하지 않지만 간단한 코드의 경우 다음 코드가 작동합니다. Reflection을 사용하여 DataRowExtensions 클래스의 메서드 필드를 호출하기 만하면됩니다.

//creating a fake table, use the one you have 
      DataTable fakeTable = new DataTable(); 
      fakeTable.Columns.Add(new DataColumn("Name",typeof(string))); 
      fakeTable.Rows.Add(new object[]{"John Doe"}); 
      DataRow r= fakeTable.Rows[0]; 

      //change to the type of the field you want to retrieve from the data row 
      var myType = typeof(string); 
      //change to the column name you want retrieve from the data row 
      var columnName = "Name"; 

      //getting the extensor method T DataRowExtensions.Field<T>(this DataRow dr,string columnName) 
      MethodInfo genericMethod = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(string) }); 
      MethodInfo method = genericMethod.MakeGenericMethod(myType); 
      //as the extensor method is static, instance is not need so just pass null 
      var result = method.Invoke(null,new object[]{ r, columnName}); 

      Console.WriteLine(result); 
+0

사실 매개 변수로 전달할 필요가있는 "Where"의 데이터 테이블을 리플렉션으로 차례로 호출합니다. 여전히 "Expression Tree"를 사용하는 다른 솔루션이 있습니다. – We0orad

관련 문제