2017-06-16 229 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语句的第一个参数。