c# - Visual studio C# VSTO: Refactoring

来自 Visual basic,我有点怀念 C# 中缺少的 With 语句,我正在寻找重构代码的方法,使其不那么拥挤。

我有以下代码:

Globals.Ribbons.RibbonMain.chkCalculation.Checked = (Globals.ThisAddIn.Application.Calculation == Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic);
Globals.Ribbons.RibbonMain.chkScreenUpdating.Checked = Globals.ThisAddIn.Application.ScreenUpdating;
Globals.Ribbons.RibbonMain.chkEvents.Checked = Globals.ThisAddIn.Application.EnableEvents;
Globals.Ribbons.RibbonMain.chkDisplayAlerts.Checked = Globals.ThisAddIn.Application.DisplayAlerts;

如何提取共同点以精简代码以使其更易读?

我的想法是创建下面的 2 个变量,但我不知道我应该使用的变量类型。有什么地方可以寻找变量类型吗?

variableType R = Globals.Ribbons.RibbonMain
variableType A = Globals.ThisAddIn.Application

回答1

var 应该可以正常工作,让编译器找出类型:

var R = Globals.Ribbons.RibbonMain;
    var A = Globals.ThisAddIn.Application;
    
    R.chkCalculation.Checked = (A.Calculation == Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic);
    R.chkScreenUpdating.Checked = A.ScreenUpdating;
    R.chkEvents.Checked = A.EnableEvents;
    R.chkDisplayAlerts.Checked = A.DisplayAlerts;

回答2

感谢@madreflection 分享知识。

当我在多个地方使用这两个变量时,我将它们提取为静态变量。

using EXCEL = Microsoft.Office.Interop.Excel;

    internal class clsMacros
    {
        //GLOBAL VARIABLES
        static RibbonMain RIBBON = Globals.Ribbons.RibbonMain;
        static EXCEL.Application APPLICATION = Globals.ThisAddIn.Application;

        public static void GetStatus()
        {
            RIBBON.chkCalculation.Checked = (APPLICATION.Calculation == EXCEL.XlCalculation.xlCalculationAutomatic);
            RIBBON.chkScreenUpdating.Checked = APPLICATION.ScreenUpdating;
            RIBBON.chkEvents.Checked = APPLICATION.EnableEvents;
            RIBBON.chkDisplayAlerts.Checked = APPLICATION.DisplayAlerts;        
        }
    }

相似文章

最新文章