gpt4 book ai didi

c# - 如何在 C# 中从 ASP.NET MVC Controller 调用静态方法

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:32 25 4
gpt4 key购买 nike

如果从 ASP .NET MVC Controller 调用,GetMethod 找不到公共(public)静态方法。(从控制台应用程序它工作正常)。

要解决此虚拟 SaveEntityGenericWrapper 方法。

如何从代码中删除 SaveEntityGenericWrapper

为什么 GetMethod("SaveEntityGeneric") 返回 nullGetMethod("SaveEntityGenericWrapper") 有效如果从 ASP .NET MVC 2 Controller 调用?

如果在 MVC2 中使用部分信任,如何使 SaveEntityGeneric 私有(private)化?

public class EntityBase() {

public void SaveEntity(EntityBase original)
{
var method = GetType().GetMethod("SaveEntityGenericWrapper");
// why this line returns null if called from ASP .NET MVC 2 controller:
// method = GetType().GetMethod("SaveEntityGeneric");
var gm = method.MakeGenericMethod(GetType());
gm.Invoke(this, new object[] { original, this });
}

// Dummy wrapper reqired for mvc reflection call only.
// How to remove it?
public List<IList> SaveEntityGenericWrapper<TEntity>(TEntity original, TEntity modified)
where TEntity : EntityBase, new()
{
return SaveEntityGeneric<TEntity>(original, modified);
}

public static List<IList> SaveEntityGeneric<TEntity>(TEntity original, TEntity modified)
where TEntity : EntityBase, new()
{ ... actual work is performed here }
}

最佳答案

您需要在 GetMethod 中指定 BindingFlags调用以便返回静态方法(我认为默认情况下只返回公共(public)实例方法)

 var method = GetType().GetMethod("SaveEntityGenericWrapper",
BindingFlags.Static|BindingFlags.Public);

关于c# - 如何在 C# 中从 ASP.NET MVC Controller 调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7406891/

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