0

我有一类查询

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查询的返回字符串?

非常感谢任何和所有帮助。

4

1 回答 1

0

我将我的属性声明转换为方法声明(感谢上面评论中的 John Doe)

从:

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 Display FROM [Names] ORDER BY [CombinedName]

这行得通。

我缺少的是传递类名作为 Invoke 语句的第一个参数。

于 2017-07-26T03:49:38.390 回答