gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:11:02 28 4
gpt4 key购买 nike

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

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

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);
}

我试过了,但没有成功。我可以在我正在调用的另一种方法中调用“AddAppUserBasic”,但它正在调用本地方法。不是封印级的那种。

最佳答案

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

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

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

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
}

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

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

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

关于c# - 访问密封类 C# 中的内部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43802790/

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