![](/img/trans.png)
[英]Why calling non-static method inside a static method in C# possible via class instance
[英]C# calling a public non-static method using reflection without instantiating its class
在C#中是否可以在不實例化其類的情況下調用方法(非靜態),例如:
public class MyClass
{
public void MyMethod()
{
Console.WriteLine("method called");
}
}
我已經使用System.Reflection.Emit命名空間嘗試了此方法,我將MyMethod()的IL復制到了動態方法中,但是出現了一個異常:
檢測到FatalExecutionEngineError:運行時遇到致命錯誤。 錯誤的地址位於線程0x2650上的0x5dceccf5。 錯誤代碼為0xc0000005。 此錯誤可能是CLR或用戶代碼中不安全或不可驗證部分的錯誤。 該錯誤的常見來源包括COM-interop或PInvoke的用戶封送處理錯誤,這些錯誤可能會破壞堆棧。
Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
Type t = a.GetType("Tutorial.MyClass");
MethodInfo m = t.GetMethod("MyMethod");
MethodBody mb = m.GetMethodBody();
DynamicMethod dm = new DynamicMethod("MethodAlias", null, Type.EmptyTypes, typeof(Tutorial.MainWindow), true);
DynamicILInfo ilInfo = dm.GetDynamicILInfo();
SignatureHelper sig = SignatureHelper.GetLocalVarSigHelper();
ilInfo.SetLocalSignature(sig.GetSignature());
ilInfo.SetCode(mb.GetILAsByteArray(), mb.MaxStackSize);
try
{
dm.Invoke(this, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
謝謝
從來沒聽說過。 因為它不是靜態的。
我只想說“不”,但我的回答還不夠長。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.