AX7: Accessing private\protected class methods and members from extension code

All class member variables are protected by default in AX 7, so it is impossible to access them from extensions. It becomes a real problem when you try to extend classes like SalesLineType.

For example, we want to add custom logic on sales line insert event. Call to super() is commented out so we cannot create pre or post event handlers. We may try to create event handlers for SalesLineType.insert() mehtod, but we won’t get access to salesLine buffer because this variable is protected.

There are two options: use overlaying or use reflection.

Overlaying is preferable approach, but today we will talk about reflection to explain this option.

Reflection is usually used for unit testing in case you need to cover protected or private code and it is hard to call this code using public API.

It has bunch of disadvantages:

It breaches entire basis of OO programming. Slow performance. Possible issues with future updates. Private methods could be changed at any time. However, once you may get into situation where it could be еру only option so it’s better to know about this possibility.

Let’s try to change some fields on sales line insert using reflection.

Create new event handler class for SalesLineType and subscribe to post insert:

复制代码
using System.Reflection;
 
/// <summary>
/// Handles events raised by <c>SalesLineTypeEventHandler</c> class.
/// </summary>
public class SalesLineTypeEventHandler
{
    [PostHandlerFor(classStr(SalesLineType), methodStr(SalesLineType, insert))]
    public static void SalesLineType_Post_insert(XppPrePostArgs _args)
    {
        SalesLineType salesLineType = _args.getThis();
 
        var bindFlags = BindingFlags::Instance | BindingFlags::NonPublic;
 
        var field = salesLineType.GetType().GetField("salesLine", bindFlags);
 
        SalesLine salesLine = field.GetValue(salesLineType);
 
        if (salesLine)
        {
            salesLine.MyNewField = 42;
            salesLine.doUpdate();
        }
    }
}
复制代码

Also we can call private or protected method:

var bindFlags = BindingFlags::Instance | BindingFlags::NonPublic;
 
var methodInfo = salesLineType.GetType().GetMethod(methodStr(SalesLineType, checkQuantityUpdate), bindFlags);
 
if (methodInfo)
{
    methodInfo.Invoke(salesLineType,  new System.Object[0]());
}

You can read more about reflection on msdn

posted @   adingkui  阅读(257)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示