gpt4 book ai didi

c# - 在静态类上调用重载的泛型方法

转载 作者:行者123 更新时间:2023-12-02 05:43:23 25 4
gpt4 key购买 nike

我正在尝试调用 InputExtensions 上的方法静态类,以便为 HtmlHelper 类上的方法创建重载。

所以无论如何,我仍然无法调用InputExtensions 类的方法。这是我用来执行此操作的部分代码:

    Type inputExtensions = typeof(InputExtensions);
MethodInfo methodInfo = null;
MethodInfo genericMethod = null;
switch (propertyViewingMode.ViewingLevel)
{
case 1:
methodInfo = inputExtensions.GetMethod(methodName, new Type[] { typeof(HtmlHelper<TModel>), typeof(Expression<Func<TModel, TProperty>>), typeof(Object) });
genericMethod = methodInfo.MakeGenericMethod(typeof(TModel), typeof(TProperty));
result = genericMethod.Invoke(null, new object[] { helper, expression, new { @class = "readOnly", @readonly = "read-only" } }) as MvcHtmlString;
break;
case 2:
methodInfo = inputExtensions.GetMethod(methodName, new Type[] { typeof(HtmlHelper<TModel>), typeof(Expression<Func<TModel, TProperty>>) });
genericMethod = methodInfo.MakeGenericMethod(typeof(TModel), typeof(TProperty));
result = genericMethod.Invoke(null, new object[] { helper, expression }) as MvcHtmlString;
break;
default:
result = new MvcHtmlString(String.Empty);
break;
}

问题是 methodInfo 始终为 null,这意味着 Type.GetMethod 找不到我尝试调用的方法。

更新:请注意,当我没有为 GetMethod 方法提供 Type[] 数组时,它会抛出异常告诉我调用不明确。

更新 2:这是我尝试调用的方法:

TextBoxFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, Object)

回答:

    Type inputExtensions = typeof(InputExtensions);
IEnumerable<MethodInfo> methods = null;
MethodInfo genericMethod = null;
MethodInfo methodInfo = null;
switch (propertyViewingMode.ViewingLevel)
{
case 1:
methods = inputExtensions.GetMethods().Where(m => m.IsGenericMethod && m.Name.Equals(methodName))
.Where(x => x.GetParameters().Count() == 3);
methodInfo = methods.FirstOrDefault(x => x.GetParameters()[2].ParameterType.FullName == "System.Object");
if (methodInfo != null)
{
genericMethod = methodInfo.MakeGenericMethod(new[] { typeof(TModel), typeof(TProperty) });
result = genericMethod.Invoke(null, new object[] { helper, expression, new { @class = "readOnly", @readonly = "read-only" } }) as MvcHtmlString;
}
break;
case 2:
methods = inputExtensions.GetMethods().Where(m => m.IsGenericMethod && m.Name.Equals(methodName))
.Where(x => x.GetParameters().Count() == 2);
methodInfo = methods.FirstOrDefault();
if (methodInfo != null)
{
genericMethod = methodInfo.MakeGenericMethod(new[] { typeof(TModel), typeof(TProperty) });
result = genericMethod.Invoke(null, new object[] { helper, expression }) as MvcHtmlString;
}
break;
default:
result = new MvcHtmlString(String.Empty);
break;
}

最佳答案

不幸的是,似乎不可能... http://blogs.msdn.com/b/yirutang/archive/2005/09/14/466280.aspx

你唯一能做的就是迭代所有给定名称的方法并自己分析参数类型:(

关于c# - 在静态类上调用重载的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10634988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com