对象 returns 参数字符串上的调用方法 - 反射 C#

Calling method on object returns parameter string - Reflection C#

我正在尝试使用反射来调用对象上的方法,并且可能涉及参数。当没有指定参数时,代码可以完美运行,但是 returns 有参数时数据错误。

这是我的代码:

object temp = readerTask.GetType().GetProperty(bsplit[0]).GetValue(readerTask, null);

if (useParams)
{
    MethodInfo methodInfo = temp.GetType().GetMethod(bsplit[1].Split(new char[] { '(' })[0], new[] { typeof(string) });
    string p = bsplit[1].Split(new char[] { '(', ')' })[1];
    value = methodInfo.Invoke(temp, new[] { p });
}
else
{
    value = temp.GetType().GetMethod(bsplit[1]).Invoke(temp, null);
}

举个例子,我的输入字符串是Date.ToString("MMMM dd, yyyy").

对象 temp 中有我想要格式化的正确日期对象,但是当我 运行 通过代码时,值变量中的数据是 MMMM dd, yyyy

如何获得 运行 的方法并正确使用参数?

p 不是 "MMMM dd, yyyy",而是 "\"MMMM dd, yyyy\""

可以很容易地用 Console.WriteLine(DateTime.Now.ToString("\"MMMM dd, yyyy\"")); 检查它是否准确打印 "MMMM dd, yyyy"

您应该删除 '"' 个符号:

MethodInfo methodInfo = temp.GetType().GetMethod(bsplit[1].Split(new char[] { '(' })[0], new[] { typeof(string) });
string p = bsplit[1].Split(new char[] { '(', ')' })[1];
if (p[0] = '"')
{
    p = p.Substring(1, p.Length - 2);
}
value = methodInfo.Invoke(temp, new[] { p });