访问密封类 C# 中的内部方法

Ard*_*den 1 c# methods class internal sealed

我正在尝试访问密封类中的内部方法,但由于它是密封类,因此我无法继承内部方法。我正在研究的解决方案的后端部分就是这样设计的。

我找到了一个解决这个问题的方法,它使用了类的扩展

public static class LocalizationsManagerExtension
{
    public static string AddAppUserBasic(this LocalizationsManager objDotnet, AppUser newUser, string pword)
    {
        try
        {
            objDotnet.AddAppUserBasic(newUser, pword);
            return "Success!";
        }
        catch(Exception ex)
        {
            return ex.Message;
        }
        //return IdentityResult.Success;
        //return System.Threading.Tasks.Task.Run();
        //return "Welcome to the World of DotNet....Mr. " + password;
    }
}

 public ActionResult UserAddNew(UserAddNewModel model)
    {
        if (ModelState.IsValid)
        {

            var user = new DataAccess.AppUser();
            user.Name = model.username;
            user.Password = model.password;
            user.DeveloperRole = model.isDeveloperRole;
            user.AdministratorRole = model.isAdministratorRole;
            user.TranslatorRole = model.isTranslatorRole;
            user.IsDomainUser = model.IsDomainUser;
            user.ManagerRole = model.isManagerRole;
            user.State = Data.Framework.Repository.Helpers.ObjectState.Added;

            var result = LM.AddAppUserBasic(user, user.Password);
            if (result == "Success!")
            {
                ViewBag.ReturnUrl = "/Usermanagement/UserLogin";
                //return RedirectToAction("UserLogin", "UserManagement");
            }
            else {  }
        }


        // If we got this far, something failed, redisplay form
        return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

我试过这个,但没有运气。我可以在我正在调用的另一种方法中调用“AddAppUserBasic”,但它正在调用本地方法。不是密封班的那个。

Ada*_*cki 6

您不得访问类中的内部方法。内部方法是内部的,这是有原因的。如果您认为您应该使用内部方法 - 首先与其他程序员谈谈他/她为什么将此方法设为内部方法。也许是误会。如果没有,请询​​问您是否应该使用其他公共方法。

如果您出于某种原因真的真的很想使用该方法,并且您知道自己在做什么

您可以使用反射来做到这一点:

using System.Reflection;

Type t = typeof(YourSealedClass); //get the type of your class
YourSealedClass obj = new YourSealedClass(); //somehow get the instance of the class

//find all non public methods
MethodInfo[] methods = t.GetMethods(BindingFlags.NonPublic|BindingFlags.Instance);

//next find your method. You can use LINQ or good old loop:
foreach(MethodInfo mi in methods)
  if(mi.Name == "MethodYouWantToUse")
  {
    mi.Invoke(obj, null);
    break; //leave the loop
  }
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关 Invoke 的更多信息:https : //msdn.microsoft.com/pl-pl/library/a89hcwhh(v= vs.110).aspx

很简单——如果你调用 Invoke,你必须传递类的对象和方法的参数——如果有的话。

但请记住 - 这样做你可能会把事情搞砸。

  • 调用内部方法是完全合法的。是的,如果你不知道自己在做什么,那就会灰心丧气。但是,例如,如果您拥有源代码,并且您使用的是版本锁定库,并且需要这些方法……那么实际上没有理由避免它。我希望人们不再讨厌它。内部不断被开发人员错误地使用和滥用,因此有大量的代码不需要也不应该是内部的。反射通常是修复代码的唯一方法。 (2认同)