[英]Access internal method in a sealed class C#
我正在尝试在密封类中访问内部方法,但是由于它是密封类,因此我无法继承内部方法。 我正在研究的解决方案的后端部分就是这样设计的。
我为此找到了解决方法,它使用了类的扩展
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”,但它正在调用本地方法。 不是密封类的人。
您不得在类中访问内部方法。 内部方法是内部的,这是有原因的。 如果您认为应该使用内部方法,请先与其他程序员讨论为什么他/她将此方法设置为内部方法。 也许是错误的。 如果不是,请询问是否应使用其他公共方法。
如果您确实真的出于某种原因想要使用该方法, 并且您知道自己在做什么
您可以使用反射来做到这一点:
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
}
您可以在此处阅读有关Invoke的更多信息: https : //msdn.microsoft.com/pl-pl/library/a89hcwhh(v= vs.110).aspx
简单-如果调用Invoke,则必须传递方法的类和参数的对象-如果有的话。
但是请记住-这样做可能会使事情搞砸。
与普遍的看法相反,有一种方法可以访问类的内部方法。 问题是您真的不应该这样做 。
在某些情况下这可能不起作用,但是可以使用此示例证明这一概念。 让我们从一个具有内部方法的密封类开始:
namespace ClassLibrary1
{
public sealed class SealedInternalExample
{
internal void TryAndExecuteMe (int someNumber)
{
System.Console.WriteLine("Internal method executed. Parameter: {0}",
someNumber);
}
}
}
您无法通过常规调用约定执行SealedInternalExample.TryAndExecuteMe
。 但是您可以通过反射来实现:
namespace CallInternalExample
{
class Program
{
static void Main(string[] args)
{
var classInstance = new SealedInternalExample();
var methods = classInstance.GetType().GetMethods(
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance);
for (int x = 0; x < methods.Length; x++)
System.Console.WriteLine("{0}: {1}", x, methods[x].Name);
var internalMethod = methods.FirstOrDefault
((m) => m.Name.Equals("TryAndExecuteMe",
StringComparison.InvariantCulture));
internalMethod.Invoke(classInstance, new object[] { 15 });
}
}
}
该程序的输出为:
0: TryAndExecuteMe
1: ToString
2: Equals
3: GetHashCode
4: GetType
5: Finalize
6: MemberwiseClone
Internal method executed. Parameter: 15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.