C# 将SystemAction委托为构造函数参数

C# 将SystemAction委托为构造函数参数,c#,winforms,interface,C#,Winforms,Interface,我有一个winform,我正在工作,它需要在到达特定阶段时更改标签,在完成时更改相同的标签。我有一个接口设置和一个实现这个接口的类。在类构造函数中,我试图将操作添加为参数,但在处理使其正确流动所需的操作时遇到问题 永远无法让它工作://而你的例子我不能给出具体的例子,因为它让我困惑。我仍然可以回答一些问题 这有用吗 private Action _methodOnProgress; public ChipLoadFirmware(Action method)

我有一个winform,我正在工作,它需要在到达特定阶段时更改标签,在完成时更改相同的标签。我有一个接口设置和一个实现这个接口的类。在类构造函数中,我试图将操作添加为参数,但在处理使其正确流动所需的操作时遇到问题


永远无法让它工作://

而你的例子我不能给出具体的例子,因为它让我困惑。我仍然可以回答一些问题

这有用吗

        private Action _methodOnProgress;
        public ChipLoadFirmware(Action method)
        {
            _methodOnProgress = method;
        }
        public bool LoadFirmWare()
        {
            (p) = > 
            {
                _methodOnProgress();
            }
        }

也许这里的事件模式更可靠

首先添加一个

public event EventHandler Progress
添加到ChipLoadFirmware类,并在manager类中公开(假设它名为manager,ChiLoad实例名为Loader)

因此,当您在添加的表单中引用管理器时

Manager.Loader.Progress += (o, e) => { /* Change the label */  };
最后在(p)=>{}do中

Progress(this, EventArgs.Empty); 
编辑这是您的更改代码,如果类表单是您的表单,则标签更改必须更改的标签

/// <summary>
/// Represents an object that can load the firmware
/// </summary>
public interface ILoadFirmware
{
    /// <summary>
    /// Loads firmware on a device
    /// </summary>
    bool LoadFirmware();
    event EventHandler Progress;
    event EventHandler Status;
}

public class ChipLoadFirmware : ILoadFirmware
{
    private readonly log4net.ILog logger = Logging.Log4NetManager.GetLogger();
    private readonly ImageLoader imageLoader = new ImageLoader ();
    private bool abort = false;
    private string cmdText = string.Empty;
    private string errortext = string.Empty;
    private string isaIp;
    public event EventHandler Progress;
    public event EventHandler Status;

    /// <summary>
    /// Sets up an ImageLoader
    /// </summary>
    /// <param name="isaTargetIpAddress">The IP address of the ISA to load the firmware on</param>
    public ChipLoadFirmware (string isaTargetIpAddress)
    {
        this.isaIp = isaTargetIpAddress;
        imageLoader.EventHandler += (s, e) => { };
        logger.DebugFormat("Using IP Address {0}", isaTargetIpAddress);
    }

    /// <summary>
    /// Loads the firmware onto the device
    /// </summary>
    /// <returns>Returns true if successful</returns>
    public bool LoadFirmware()
    {
        bool result = imageLoader.Run(this.isaIp,
            false,
            Command.Command,
            string.Empty,
            CommandFlag.CommandFlag,
            2000,
            (p) => { Progress(this, EventArgs.Empty); },
            (s) => { Status(this, EventArgs.Empty); },
            ref this.abort,
            out this.cmdText,
            out this.errortext);

        if (!result)
        {
            result = false;
            throw new InvalidOperationException(
                string.Format(
                    "ImageLoader failed with message: {0}",
                    errortext));
        }

        return result;
    }
}

public class CalibrationManager : ICalibrationManager
{
    const uint startAddress = 0x00000000;
    const uint startAddress = 0x00000000;

    private readonly log4net.ILog logger;
    private readonly ISignalGenerator sigGenerator;
    public readonly ILoadFirmware loadFirmware;
    private readonly IReader reader;
    private readonly IValueParser valueParser;
    private readonly IRepository<CalibrationValue> calibrationRepository;
    private readonly IRepository<UIDList> uidRepository;

    private string uid;

    public CalibrationManager(ISignalGenerator sigGen, ILoadFirmware loadFirmware, IReader chipRreader, IValueParser chipValueParser, IRepository<UIDList> uidRepo, IRepository<CalibrationValue> calRepo)
    {
        if (sigGen == null ||
            loadFirmware == null ||
            chipReader == null ||
            chipValueParser == null ||
            calRepo == null ||
            uidRepo == null) throw new ArgumentNullException();

        logger = Logging.Log4NetManager.GetLogger();

        this.sigGenerator = sigGen;
        this.loadFirmware = loadFirmware;
        this.reader = chipReader;
        this.valueParser = chipValueParser;
        this.uidRepository = uidRepo;
        this.calibrationRepository = calRepo;
    }

    public void Calibrate(bool reuse)
    {
        int voltageG;
        int currentG;
        // Read uid from device
        this.uid = uidReader.ReadUid();
        logger.DebugFormat("Read UID {0}", this.uid);

        var possibleCalibrations = getCalibrationDataFromRepo();
        if (possibleCalibrations.Any() && reuse)
        {
            logger.Debug("Reusing existing values");
            var existingCalibration = possibleCalibrations.OrderByDescending(c => c.DateCalibrated).First();
            currentG = existingCalibration.CurrentGain;
            voltageG = existingCalibration.VoltageGain;
        }
        else
        {
            logger.Debug("Reading new values");

            // Set voltage and current for signal generator
            sigGenerator.SetOutput(187, 60);

            // Load firmware onto chip for CLI commands
            loadFirmware.LoadFirmware();
            UpdateStateChange(StateOfDevice.LoadFirmware);

            // Read voltage from device and calibrate
            voltageG = valueParser.ReadVoltageValue();
            UpdateStateChange(StateOfDevice.CalibrateVoltage);

            // Read current from device and calibrate
            sigGenerator.SetOutput(38, 60);
            currentG = valueParser.ReadCurrentValue();
            UpdateStateChange(StateOfDevice.CalibrateCurrent);

            // Insert values into table
            CalibrationValue cv = new CalibrationValue();
            cv.UidId = uidRepository.GetBy(e => e.UID.Equals(this.uid)).Id;
            cv.CurrentGain = currentG;
            cv.VoltageGain = voltageG;
            calibrationRepository.Insert(cv);
            calibrationRepository.Submit();
            UpdateStateChange(StateOfDevice.DatabaseInsert);
        }

        logger.DebugFormat("Updated database for current gain to {0} and voltage gain to {1}", currentG, voltageG);

        // Once here, device has passed all phases and device is calibrated
        UpdateStateChange(StateOfDevice.CalibrationComplete);
    }

    private IQueryable<CalibrationValue> getCalibrationDataFromRepo()
    {
        int uidId = uidRepository.GetBy(e => e.UID.Equals(this.uid)).Id;
        return calibrationRepository.SearchFor(c => c.UidId == uidId);
    }

    public bool CalibrationDataExists()
    {
        this.uid = uidReader.ReadUid();
        logger.DebugFormat("Read UID {0}", this.uid);

        return getCalibrationDataFromRepo().Any();
    }

    public event Action<StateOfDevice, string> StateChange;

    private void UpdateStateChange(StateOfDevice state, string message = "")
    {
        var sc = StateChange;
        if (sc != null)
        {
            StateChange(state, message);
        }
    }
}

public class Form
{
    Label labelToModify;

    void MagickButtonClick(object Source, EventArgs e)
    { 

        CalibrationManager manager = new CalibrationManager(.......);

        manager.loadFirmware.Progress += (o, e) => { labelToModify.Text = "Some progress achieved!!";  };

    }

}
//
///表示可以加载固件的对象
/// 
公共接口ILOAD固件
{
/// 
///在设备上加载固件
/// 
bool加载固件();
事件处理程序进度;
事件处理程序状态;
}
公共类ChipLoadFirmware:ILoadFirmware
{
私有只读log4net.ILog logger=Logging.Log4NetManager.GetLogger();
私有只读ImageLoader ImageLoader=新ImageLoader();
私有布尔中止=假;
私有字符串cmdText=string.Empty;
私有字符串errortext=string.Empty;
私有字符串isaIp;
公共事件处理程序进度;
公共事件事件处理程序状态;
/// 
///设置图像加载器
/// 
///要加载固件的ISA的IP地址
公共芯片加载固件(字符串IsTargetIPAddress)
{
this.isaIp=isTargetIPAddress;
imageLoader.EventHandler+=(s,e)=>{};
DebugFormat(“使用IP地址{0}”,isTargetIPAddress);
}
/// 
///将固件加载到设备上
/// 
///如果成功,则返回true
公共bool加载固件()
{
bool result=imageLoader.Run(this.isaIp,
错误的
命令,命令,
字符串。空,
CommandFlag.CommandFlag,
2000,
(p) =>{Progress(this,EventArgs.Empty);},
(s) =>{Status(this,EventArgs.Empty);},
参考此。中止,
输出此.cmdText,
输出此.errortext);
如果(!结果)
{
结果=假;
抛出新的InvalidOperationException(
字符串格式(
“ImageLoader失败,消息为:{0}”,
错误文本);
}
返回结果;
}
}
公共类校准管理器:ICalibrationManager
{
Constuint startAddress=0x00000000;
Constuint startAddress=0x00000000;
专用只读log4net.ILog记录器;
专用只读ISignalGenerator;
公共只读ILoadFirmware loadFirmware;
专用只读IReader阅读器;
私有只读IValueParser-valueParser;
专用只读iReposition校准存储库;
私人只读易读易读易读;
私有字符串uid;
公共校准管理器(ISignalGenerator sigGen、ILoadFirmware loadFirmware、IReader芯片阅读器、IValueParser芯片值分析器、IRepository uidRepo、IRepository calRepo)
{
如果(sigGen==null||
loadFirmware==null||
芯片读取器==null||
chipValueParser==null||
calRepo==null||
uidRepo==null)抛出新的ArgumentNullException();
logger=Logging.Log4NetManager.GetLogger();
this.sigGenerator=sigGen;
this.loadFirmware=loadFirmware;
this.reader=芯片阅读器;
this.valueParser=chipValueParser;
this.uidRepository=uidRepo;
this.calibrationRepository=calRepo;
}
公共空间校准(bool重用)
{
内电压;
int-currentG;
//从设备读取uid
this.uid=uidReader.ReadUid();
DebugFormat(“readuid{0}”,this.UID);
var-possibleCaliversions=getCalibrationDataFromRepo();
if(可能的校准.Any()&重用)
{
调试(“重用现有值”);
var existingCalibration=possibleCalibrations.OrderByDescending(c=>c.DateCalibration).First();
currentG=现有校准。CurrentGain;
电压G=现有校准。电压增益;
}
其他的
{
调试(“读取新值”);
//设置信号发生器的电压和电流
sigGenerator.SetOutput(187,60);
//将固件加载到CLI命令的芯片上
loadFirmware.loadFirmware();
UpdateStateChange(StateOfDevice.LoadFirmware);
//从设备读取电压并校准
voltageG=valueParser.ReadVoltageValue();
UpdateStateChange(StateOfDevice.CalibrateVoltage);
//从设备读取电流并校准
sigGenerator.SetOutput(38,60);
currentG=valueParser.ReadCurrentValue();
UpdateStateChange(设备状态校准电流);
//在表中插入值
CalibrationValue cv=新的CalibrationValue();
cv.UidId=uidRepository.GetBy(e=>e.UID.Equals(this.UID)).Id;
cv.CurrentGain=电流G;
cv.电压增益=电压g;
校准存储库。插入(cv);
calibrationRepository.Submit();
UpdateStateChange(StateOfDevice.DatabaseInsert);
}
DebugFormat(“更新了{0}电流增益和{1}电压增益的数据库”,currentG,voltageG);
//一旦到了这里,设备就通过了所有阶段和开发