簡體   English   中英

擴展方法的反思

[英]reflection on an extension method

現在是兩個小時,我正在嘗試對擴展方法進行一些思考。 我想要的是稱為DataRow的通用靜態方法“ Field”,但我沒有成功。 誰能幫我 ?

這是我的代碼:

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);

嘗試:

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

static方法上使用Expression.Call時,第一個參數應作為null傳遞。 該實例實際上是一個參數。

我不確定為什么要在代碼中使用Expression,但是對於簡單的東西,以下代碼可以工作。 它僅使用反射在類DataRowExtensions上調用方法Field。

 //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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM