我开发了一个自动显微镜系统的驱动程序,用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;
Objective
是Get
类中的Set
/ Scope
属性。
关于为什么C#属性的Set
在MATLAB try
/ catch
语句中无法正常执行的任何想法?
更多详情
我进一步描述了MATLAB中的行为。
try
/ catch
运算符中,每行也会按预期执行。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
有什么想法吗?
答案 0 :(得分:1)
我尝试使用小型组装,但我无法重现这个问题:
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中使用它的代码:
>> 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中,尽管有办法capture the output from .NET)