2017-06-16 67 views
0

我在GetMethod()返回null

public class gridQueries 
{ 
    .... 

    public string propertiesCombinedNamesQuery { get; set; } = 
     "SELECT [NameId], [CombinedName] AS Display FROM [Names] ORDER BY [CombinedName]"; 
    .... 
} // end class gridQueries 

一類查詢的另一種方法,我得到這個查詢的名稱的字符串,然後嘗試調用它,但GetMethod()總是返回null

// Get the short name of the dependent field from the dictionary value[2] string 
string _1DF_Name = addEditFieldControl.FirstOrDefault(p => p.Value[1].Contains(fieldShortName)).Key; 
// Find the long name of the dependent field 
string Value1Text = addEditFieldControl.FirstOrDefault(p => p.Key.Contains(_1DF_Name)).Value[1]; 

這給了我一個字符串,它看起來像這樣 「_Q_propertiesCombinedNamesQuery_OwnerName」

// Couldn't get invoke to work. 
// because MethodInfo info is null after the GetMethod() call 

string queryMethod = ""; 
queryMethod = "queries."+strIsBtwTags(Value1Text, "_Q_", "_"); 
Type queriesType = queryMethod.GetType(); 
MethodInfo info = queriesType.GetMethod(queryMethod); 

string query = info.Invoke(null, null).ToString(); 

任何人能發現我究竟做錯了什麼? 或建議一種方法來調用這個字符串作爲一種方法,以便我得到返回字符串與SQL查詢在裏面?

任何和所有的幫助,非常感謝。

+1

'propertiesCombinedNamesQuery'不是一種方法。這是一個財產。而且,這裏的大部分代碼都是不相關的。要麼'queryMethod'包含錯誤的字符串(因此問題將與'GetMethod'無關),或者它包含* correct *字符串,但'GetMethod'返回null;在這種情況下,您可以簡單地將其作爲簡化示例進行硬編碼,並刪除不相關的代碼。 – Rob

回答

0

我轉換我的財產語句轉換的方法聲明(謝謝李四上述評論)

來源:

public class gridQueries 
{ 
    .... 
    public string propertiesCombinedNamesQuery { get; set; } = 
     "SELECT [NameId], [CombinedName] AS Display FROM [Names] ORDER BY [CombinedName]"; 
    .... 
} 

要:

public class gridQueries 
{ 
    .... 
    public string propertiesCombinedNamesQuery() 
    { 
     return "SELECT [NameId], [CombinedName] AS Display FROM [Names] ORDER BY [CombinedName]"; 
    } 
    .... 
} 

從我的節目,我調用方法

// Top of program 
using System.Reflection; 
.... 
.... 
string qstring = "propertiesCombinedNamesQuery"; 
string query = "" 

gridQueries q2 = new gridQueries(); 
MethodInfo methodInfo = q2.GetType().GetMethod(qstring); 
query = (string)methodInfo.Invoke(q2, null); 
.... 

查詢現在包含「SELECT [NameId],[CombinedName] AS顯示FROM [Names] ORDER BY [CombinedName]」

這是有效的。

我所缺少的是傳遞類名作爲Invoke語句的第一個參數。