簡體   English   中英

c#多種功能的動作動態參數

[英]c# Action dynamic parameters for multiple functions

我的項目中有多個功能完全相同的功能,這些功能之間的唯一區別是,函數簽名和在ex函數中調用的操作方法簽名中的參數不同。

   function DoSomething(string x, datatable dt, Action<string, datatable> methodname ){ methodname(x, dt);}
   function DoSomething(datatable dt1, datatable dt2, Action<datatable, datatable> methodname ){ methodname(dt1, dt2);}
   function DoSomething(Class FOO, datatable dt2, Action<class, datatable> methodname ){ methodname(FOO, dt2);}

我正在嘗試合並此代碼,以便可以讓一個函數接受任何參數並調用action方法。 我已經組合了一個將List作為參數的函數:

   List<object> list_obj = new List<object>();
   List_obj.Add(Datatable) 
   List_obj.Add(Class FOO)
   function DynamicDoSomething<T>(Action<T> methodname, T Parameter) {methodname(Parameter)}

我的問題是將對象獲取到函數的這種工作,但是接下來我要遍歷List嘗試根據函數所需的內容創建或分配DataTables或類。 例如:

     function methodbeingcalled(List<object> objlist){
         foreach(var item in objlist){
           string ObjType = item.GetType().ToString();
                if (ObjType.Equals("System.Data.DataTable"))
                {
                    dt= ((DataTable)item);
                }
                else { foo = ((Foo)item);}
         }
     }

是他們做這件事的更好方法嗎,因為分配給foreach的方式好像是HACK

您的簽名看起來像這樣:

DoSomething<TInput>(TInput x, DataTable dt, Action<TInput, DataTable> methodname)

然后您可以這樣稱呼:

DoSomething("Some string value.", someDataTable, (input, dt) => { });

或像這樣:

DoSomething(someObject, someDataTable, (input, dt) => { });

現在在所有情況下都正確輸入了TInput

暫無
暫無

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

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