在MATLAB try/catch运算符中使用C#方法/属性

本文关键字:方法 属性 运算符 MATLAB try catch | 更新日期: 2023-09-27 18:22:08

我开发了一个自动显微镜系统的驱动程序,用C#编写,并使用Visual Studio 2013编译。在分配try/catch循环中的一些属性时,我遇到了一个特殊的问题。

下面是MATLAB代码的示例(为了显示而简化)。

pwsAssembly = NET.addAssembly ( 'file location' );
scope = Pws . Scope ( );
scope . Connect();
% This command performs the movement.
scope . Objective = 1;
% This command DOES NOT perform the movement, but DOES NOT enter the catch statement.
try
  scope . Objective = 4;
catch
  error ( 'Unable to adjust objective' );
end
% Again, this command performs the movement:
scope . Objective = 4;

ObjectiveScope类中的Get/Set属性。

关于为什么C#属性的Set在MATLAB try/catch语句中不能正确执行,有什么想法吗?

更多详细信息

我在MATLAB中进一步描述了这种行为。

  1. 如果我将代码作为脚本执行,而不中断或暂停,则会跳过一些操作
  2. 如果我"逐步"完成脚本,那么每一行都会按预期执行,即使在try/catch运算符中也是如此
  3. 如果属性分配在if语句中,则它总是成功的

以下是修改后的MATLAB代码,以反映这一观察结果。

pwsAssembly = NET . addAssembly ( 'fileLocation' );
scope = Pws . Scope ( );
scope . Connect ( );
scope . Objective = 1; % Unsuccessful. Successful if I "step" through.
try
  scope . Objective = 4; % Unsuccessful . Successful if I "step" through.
catch
  error ( 'Headaches' );
end
if ( scope . Objective  ~= 6 )
  scope . Objective = 6; % Successful, always.
end

有什么想法吗?

在MATLAB try/catch运算符中使用C#方法/属性

我尝试了一个小的组装,但无法重现问题:

Scope.cs

using System;
namespace PWS
{
    public class Scope
    {
        public int Objective { get; set; }
        public Scope()
        {
            Objective = 0;
        }
        public void Connect()
        {
            Console.WriteLine("connected");
        }
    }
}

使用将其编译为程序集

C:'> csc.exe /target:library Scope.cs

MATLAB

以下是在MATLAB中使用它的代码:

>> NET.addAssembly(fullfile(pwd,'Scope.dll'));
>> scope = PWS.Scope();
>> scope.Connect();
>> scope.Objective = 1;
>> try, scope.Objective = 4, catch ME, error('failed'); end
>> if (scope.Objective ~= 6), scope.Objective = 6; end

无论我如何运行代码,所有行都运行良好:在命令窗口中以交互方式执行,作为脚本或函数运行,无论是正常运行还是在调试器中逐步执行代码。

(注意:对Console.WriteLine的任何调用通常不会在MATLAB中显示,尽管有一些方法可以捕获.NET的输出)