簡體   English   中英

后銳第三方事件攔截

[英]Postsharp 3rd party components events interception

我有一個關於使用c#和Postsharp進行事件攔截的問題。

我想在postsharp中取消事件的執行,例如BeforeDropDown,RowSelected MouseClick和EventInterceptionAspect。

但是我找不到可以編寫代碼的合適地方。 例:

我嘗試過這樣的事情:

[Serializable]
class EventInter : EventInterceptionAspect
{
    public override bool CompileTimeValidate(System.Reflection.EventInfo targetEvent)
    {
        return "FormClosed".Equals(targetEvent.Name);
    }

    public override void OnInvokeHandler(EventInterceptionArgs args)
    {
        if condition executes method otherwise no
    }
}

形式:

[EventInter]
public partial class Frm_RomperMesa : KryptonForm

但這沒有用。 所以我想知道是否有可能實現我想要的。

非常感謝。 我希望清楚。

對的,這是可能的。 問題是,您試圖將事件攔截方面應用於另一個程序集中定義的事件,而該事件在代碼中無法執行。 您甚至無法覆蓋該事件,因為該事件的設置要使用后面的設計器代碼中的基本Form類型來處理

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);

您將必須修改裝配才能執行此操作。 使用以下方面和鏈接來修改您的

public class EventAspectProvider : TypeLevelAspect , IAspectProvider
    {
        public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
        {
            Type t = (Type)targetElement;

            EventInfo e = t.GetEvents().First(c => c.Name.Equals("FormClosing"));

            return new List<AspectInstance>() { new AspectInstance(e, new EventInter()) };
        }

    }

    [Serializable]
    public class EventInter : EventInterceptionAspect
    {

        public override void OnInvokeHandler(EventInterceptionArgs args)
        {
            int x = 0;

            if (x > 0) //Do you logic here
            {
                args.ProceedInvokeHandler();
            }
        }
    }

基本上,它歸結為修改System.Windows.Forms.dll,我不建議這樣做。 但是,如果它是其他一些第三方供應商庫,那就去吧。

一種解決方法是用另一種方法解決此問題:在掛接到事件的方法上使用一個方面,如果滿足條件,則取消該方法的正常執行。 這不會阻止引發事件表單,但是會阻止執行事件處理代碼。

[EventInter]
private void someForm_FormClosed(object sender, EventArg arg) {}

我們在項目中經常使用這種方法。 我們有幾個方面適用於事件處理方法(異常處理,游標處理等)。

我們走得更遠,在組裝級別應用方面,並使用CompileTimeValide識別事件處理方法的簽名。 從理論上講,它不是100%可靠的,但是到目前為止,我們尚未發現此方法有任何問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM