[英]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.