Net有四个判等函数(Equal ,==,refernceEqual, 以及静态Equal的区别)

.Net 有四个判等函数?不少人看到这个标题,会对此感到怀疑。事实上确是如此, .Net 提供了 ReferenceEquals 、 静态 Equals ,具体类型的 Equals 以及 == 操作符这四个判等函数。但是这四个函数之间有细微的关系,改变其中一个函数的实现会影响到其他函数 的操作结果。

 

首先要说的是 Object.ReferenceEquals Object.Equals 这两个 静态函数,对于它们俩来说,是不需要进行重写的,因为它们已经完成它们所要得做的操作。

 

对于 Object.ReferenceEquals 这个静态函数,函数形势如下:

public static bool ReferenceEquals( object left, object right );

 

这个函数就是判断两个引用类型对象是否指向同一个地址。有此说明后,就确定了它的使用范围,即只能对于引用类型操 作。那么对于任何值类型数据操作,即使是与自身的判别,都会返回 false 。这主要因为 在调用此函数的时候,值类型数据要进行装箱操作,也就是对于如下的形式来说。

    int n = 10;

    Object.ReferenceEquals( n, n );

 

这是因为对于 n 这个数据装箱两次,而每次装箱后的地址有 不同,而造成 Object.ReferenceEquals( n, n ) 的结果永远为 false

 

对于第一个判等函数来说,没有什么好扩展的,因为本身已经很好地完 成了它所要做的。

 

对于第二个 Object.Equals 这个静态函数,其形式如下:

public static bool Equals( object left, object right );

 

按照书中对它的分析,其大致函数代码如下:

    public static void Equals( object left, object right )

    {

        // Check object identity

        if ( left == right )

            return true ;

 

        // both null references handled above

        if ( ( left == null ) || ( right == null ) )

            return false ;

 

        return left.Equals( right );

    }

 

可以说, Object.Equals 这个函数完成 判等操作,需要经过三个步骤,第一步是需要根据对象所属类型的 == 操作符的执行结 果;第二步是判别是否为 null ,也是和第一步一样,需要根据类型的 == 操作符的执行结果;最后一步要使用到类型的 Equals 函数的执行结果。也就是说这个静态函数的返回结果,要取决于后面要提到的两个 判等函数。类型是否提供相应的判等函数,成为这个函数返回结果的重要因素。

 

那么对于 Object.Equals 这个静态方法来说,虽说接受参数的类型也属于引用类型,但是不同于 Object.ReferenceEquals 函数,对于如下的代码,能得出正确的结果。

    int n = 10;

    Debug.WriteLine( string .Format( "{0}", Object.Equals( n, n ) ) );

    Debug.WriteLine( string .Format( "{0}", Object.Equals( n, 10 ) ) );

 

这是因为在此函数中要用到具体类型的两个判等函数,不过就函数本身而言,该做的判断都做了,因此不需要去重载添加复 杂的操作。

 

为了更好的述说剩下两个函数,先解释一下等价的意义。对于等价的意 义,就是自反、对称以及传递。

所谓自反,即 a == a

而对称,是 a == b ,则 b == a

传递是 a == b b == c ,则 a == c

理解等价的意义后,那么在实现类型的判等函数也要满足这个等价规 则。

 

对于可以重载的两个判等函数,首先来介绍的是类型的 Equals 函数,其大致形式如下:

public override bool Equals( object right );

 

那么对于一个类型的 Equals 要做些什么操作呢,一般来说大致如下:

    public class KeyData

    {

        private int nData;

        public int Data

        {

            get { return nData;}

            set { nData = value ; }

        }

 

        public override bool Equals( object right )

        {

            //Check null

            if ( right == null )

                return false ;

 

            //check reference equality

            if ( object .ReferenceEquals( this , right ) )

                return true ;

 

            //check type

            if ( this .GetType() != right.GetType() )

                return false ;

 

            //convert to current type

            KeyData rightASKeyData = right as KeyData;

 

            //check members value

            return this .Data == rightASKeyData.Data;

        }

    }

 

如上增加了一个类型检查,即

if( this.GetType() != right.GetType() )

这部分,这是由于子类对象可以通过 as 转化成基类对 象,从而造成不同类型对象可以进行判等操作,违反了等价关系。

 

除此外对于类型的 Equals 函数来,其实并 没有限制类型非要属于引用类型,对于值类型也是可以重载此函数,但是我并不推荐,主要是 Equals 函数的参数类 型是不可变的,也就是说通过此方法,值类型要经过装箱操作,而这是比较影响效率的。

 

而对于值类型来说,我推荐使用最后一种判等函数,即重载运算符 == 函数,其大致形式如下:

public static bool operator == ( KeyData left,  KeyData right );

 

对于一个值类型而言,其的大致形式应该如下:

    public struct KeyData

    {

        private int nData;

        public int Data

        {

            get { return nData;}

            set { nData = value ; }

        }

 

        public static bool operator == ( KeyData left,  KeyData right )

        {

            return left.Data == right.Data;

        }

 

        public static bool operator != ( KeyData left, KeyData right )

        {

            return left.Data != right.Data;

        }

    }

 

由于 == 操作与 != 操作要同步定 义,所以在定义 == 重载函数的时候,也要定义 != 重载函数。这 也是 .Net 在判等操作保持一致性。那么对于最后一个判等函数,这种重载运算符的方法 并不适合引用类型。这就是 .Net 经常现象,去判断两个引用类型,不要用 == ,而要用某个 对象的 Equals 函数。所以在编写自己类型的时候,要保留这种风格。

 

那么对于以上介绍的四种判等函数,会产生如下类似的对比表格。

 

操作结果取决于

适用范围

建议

Object.ReferenceEquals

两个参 数对象是否属于同一个引用

引用类型

不要用它来判断值类型数据

Object.Equals

参数类型自身的判等函数

无限制

考虑装箱操作对值类型数据产生的影响

类型的 Equals

类型重载函数

无限制

考虑装箱操作对值类型数据产生的影响

类型的 == 重载

类型重载函数

无限制

不要在引用类型中重载此运算符

 

那么在编写类型判等函数的时候,要注意些什么呢,给出如下几点建 议。

首先,要判断当前定义的类型是否具有判等的意义;

其次,定义类型的判等函数要满足等价规则;

最后一点,值类型最好不要重载定义 Equals 函数,而引用 类型最好不要重载定义 == 操作符。

?不少人看到这个标题,会对此感到怀疑。事实上确是如此, .Net 提供了 ReferenceEquals 、 静态 Equals ,具体类型的 Equals 以及 == 操作符这四个判等函数。但是这四个函数之间有细微的关系,改变其中一个函数的实现会影响到其他函数 的操作结果。

 

首先要说的是 Object.ReferenceEquals Object.Equals 这两个 静态函数,对于它们俩来说,是不需要进行重写的,因为它们已经完成它们所要得做的操作。

 

对于 Object.ReferenceEquals 这个静态函数,函数形势如下:

public static bool ReferenceEquals( object left, object right );

 

这个函数就是判断两个引用类型对象是否指向同一个地址。有此说明后,就确定了它的使用范围,即只能对于引用类型操 作。那么对于任何值类型数据操作,即使是与自身的判别,都会返回 false 。这主要因为 在调用此函数的时候,值类型数据要进行装箱操作,也就是对于如下的形式来说。

    int n = 10;

    Object.ReferenceEquals( n, n );

 

这是因为对于 n 这个数据装箱两次,而每次装箱后的地址有 不同,而造成 Object.ReferenceEquals( n, n ) 的结果永远为 false

 

对于第一个判等函数来说,没有什么好扩展的,因为本身已经很好地完 成了它所要做的。

 

对于第二个 Object.Equals 这个静态函数,其形式如下:

public static bool Equals( object left, object right );

 

按照书中对它的分析,其大致函数代码如下:

    public static void Equals( object left, object right )

    {

        // Check object identity

        if ( left == right )

            return true ;

 

        // both null references handled above

        if ( ( left == null ) || ( right == null ) )

            return false ;

 

        return left.Equals( right );

    }

 

可以说, Object.Equals 这个函数完成 判等操作,需要经过三个步骤,第一步是需要根据对象所属类型的 == 操作符的执行结 果;第二步是判别是否为 null ,也是和第一步一样,需要根据类型的 == 操作符的执行结果;最后一步要使用到类型的 Equals 函数的执行结果。也就是说这个静态函数的返回结果,要取决于后面要提到的两个 判等函数。类型是否提供相应的判等函数,成为这个函数返回结果的重要因素。

 

那么对于 Object.Equals 这个静态方法来说,虽说接受参数的类型也属于引用类型,但是不同于 Object.ReferenceEquals 函数,对于如下的代码,能得出正确的结果。

    int n = 10;

    Debug.WriteLine( string .Format( "{0}", Object.Equals( n, n ) ) );

    Debug.WriteLine( string .Format( "{0}", Object.Equals( n, 10 ) ) );

 

这是因为在此函数中要用到具体类型的两个判等函数,不过就函数本身而言,该做的判断都做了,因此不需要去重载添加复 杂的操作。

 

为了更好的述说剩下两个函数,先解释一下等价的意义。对于等价的意 义,就是自反、对称以及传递。

所谓自反,即 a == a

而对称,是 a == b ,则 b == a

传递是 a == b b == c ,则 a == c

理解等价的意义后,那么在实现类型的判等函数也要满足这个等价规 则。

 

对于可以重载的两个判等函数,首先来介绍的是类型的 Equals 函数,其大致形式如下:

public override bool Equals( object right );

 

那么对于一个类型的 Equals 要做些什么操作呢,一般来说大致如下:

    public class KeyData

    {

        private int nData;

        public int Data

        {

            get { return nData;}

            set { nData = value ; }

        }

 

        public override bool Equals( object right )

        {

            //Check null

            if ( right == null )

                return false ;

 

            //check reference equality

            if ( object .ReferenceEquals( this , right ) )

                return true ;

 

            //check type

            if ( this .GetType() != right.GetType() )

                return false ;

 

            //convert to current type

            KeyData rightASKeyData = right as KeyData;

 

            //check members value

            return this .Data == rightASKeyData.Data;

        }

    }

 

如上增加了一个类型检查,即

if( this.GetType() != right.GetType() )

这部分,这是由于子类对象可以通过 as 转化成基类对 象,从而造成不同类型对象可以进行判等操作,违反了等价关系。

 

除此外对于类型的 Equals 函数来,其实并 没有限制类型非要属于引用类型,对于值类型也是可以重载此函数,但是我并不推荐,主要是 Equals 函数的参数类 型是不可变的,也就是说通过此方法,值类型要经过装箱操作,而这是比较影响效率的。

 

而对于值类型来说,我推荐使用最后一种判等函数,即重载运算符 == 函数,其大致形式如下:

public static bool operator == ( KeyData left,  KeyData right );

 

对于一个值类型而言,其的大致形式应该如下:

    public struct KeyData

    {

        private int nData;

        public int Data

        {

            get { return nData;}

            set { nData = value ; }

        }

 

        public static bool operator == ( KeyData left,  KeyData right )

        {

            return left.Data == right.Data;

        }

 

        public static bool operator != ( KeyData left, KeyData right )

        {

            return left.Data != right.Data;

        }

    }

 

由于 == 操作与 != 操作要同步定 义,所以在定义 == 重载函数的时候,也要定义 != 重载函数。这 也是 .Net 在判等操作保持一致性。那么对于最后一个判等函数,这种重载运算符的方法 并不适合引用类型。这就是 .Net 经常现象,去判断两个引用类型,不要用 == ,而要用某个 对象的 Equals 函数。所以在编写自己类型的时候,要保留这种风格。

 

那么对于以上介绍的四种判等函数,会产生如下类似的对比表格。

 

操作结果取决于

适用范围

建议

Object.ReferenceEquals

两个参 数对象是否属于同一个引用

引用类型

不要用它来判断值类型数据

Object.Equals

参数类型自身的判等函数

无限制

考虑装箱操作对值类型数据产生的影响

类型的 Equals

类型重载函数

无限制

考虑装箱操作对值类型数据产生的影响

类型的 == 重载

类型重载函数

无限制

不要在引用类型中重载此运算符

 

那么在编写类型判等函数的时候,要注意些什么呢,给出如下几点建 议。

首先,要判断当前定义的类型是否具有判等的意义;

其次,定义类型的判等函数要满足等价规则;

最后一点,值类型最好不要重载定义 Equals 函数,而引用 类型最好不要重载定义 == 操作符。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用MATLAB的GUI设计工具来实现这个设计界面。以下是一个简单的示例: 1. 创建一个新的GUI界面,命名为"时域分析方法设计界面"。 2. 在界面上添加一个静态文本框,用于显示电路图或者传递函数。 3. 添加一个参数修改框,用于输入电路参数或者修改传递函数的系数。 4. 添加一个按钮,用于触发分析操作。 5. 在界面上添加一个波形显示框,用于显示分析结果。 6. 在回调函数中,编写时域分析方法的MATLAB代码,根据输入参数计算分析结果,并将结果显示在波形显示框中。 下面是一个示例代码,其中包含了一个简单的RC电路的传递函数及分析方法: ```matlab function varargout = time_analysis_gui(varargin) % TIME_ANALYSIS_GUI MATLAB code for time_analysis_gui.fig % TIME_ANALYSIS_GUI, by itself, creates a new TIME_ANALYSIS_GUI or raises the existing % singleton*. % % H = TIME_ANALYSIS_GUI returns the handle to a new TIME_ANALYSIS_GUI or the handle to % the existing singleton*. % % TIME_ANALYSIS_GUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in TIME_ANALYSIS_GUI.M with the given input arguments. % % TIME_ANALYSIS_GUI('Property','Value',...) creates a new TIME_ANALYSIS_GUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before time_analysis_gui_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to time_analysis_gui_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help time_analysis_gui % Last Modified by GUIDE v2.5 17-Nov-2021 17:00:08 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @time_analysis_gui_OpeningFcn, ... 'gui_OutputFcn', @time_analysis_gui_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before time_analysis_gui is made visible. function time_analysis_gui_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to time_analysis_gui (see VARARGIN) % Choose default command line output for time_analysis_gui handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes time_analysis_gui wait for user response (see UIRESUME) % uiwait(handles.figure1); % Initialize the circuit model handles.R = 1; % resistance (ohms) handles.C = 1; % capacitance (farads) handles.tf = tf([1],[handles.R*handles.C 1]); % transfer function guidata(hObject,handles); % --- Outputs from this function are returned to the command line. function varargout = time_analysis_gui_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in analyze_button. function analyze_button_Callback(hObject, eventdata, handles) % hObject handle to analyze_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get the input signal parameters (amplitude, frequency, duration) A = str2double(get(handles.amplitude_edit,'String')); f = str2double(get(handles.frequency_edit,'String')); t = str2double(get(handles.duration_edit,'String')); % Generate the input signal (sinusoidal) tvec = linspace(0,t,1000); u = A*sin(2*pi*f*tvec); % Simulate the circuit response y = lsim(handles.tf,u,tvec); % Display the output waveform axes(handles.output_axes); plot(tvec,y); xlabel('Time (s)'); ylabel('Voltage (V)'); % --- Executes during object creation, after setting all properties. function amplitude_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to amplitude_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function amplitude_edit_Callback(hObject, eventdata, handles) % hObject handle to amplitude_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes during object creation, after setting all properties. function frequency_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to frequency_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function frequency_edit_Callback(hObject, eventdata, handles) % hObject handle to frequency_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes during object creation, after setting all properties. function duration_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to duration_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function duration_edit_Callback(hObject, eventdata, handles) % hObject handle to duration_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes during object creation, after setting all properties. function output_axes_CreateFcn(hObject, eventdata, handles) % hObject handle to output_axes (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: place code in OpeningFcn to populate output_axes % --- Executes during object creation, after setting all properties. function tf_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to tf_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function tf_edit_Callback(hObject, eventdata, handles) % hObject handle to tf_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Update the transfer function based on the new values of R and C handles.R = str2double(get(handles.resistance_edit,'String')); handles.C = str2double(get(handles.capacitance_edit,'String')); handles.tf = tf([1],[handles.R*handles.C 1]); % Update the transfer function display set(handles.tf_edit,'String',num2str(handles.tf)); % Save the updated data to the handles structure guidata(hObject,handles); % --- Executes during object creation, after setting all properties. function resistance_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to resistance_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function resistance_edit_Callback(hObject, eventdata, handles) % hObject handle to resistance_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Update the transfer function based on the new values of R and C handles.R = str2double(get(handles.resistance_edit,'String')); handles.C = str2double(get(handles.capacitance_edit,'String')); handles.tf = tf([1],[handles.R*handles.C 1]); % Update the transfer function display set(handles.tf_edit,'String',num2str(handles.tf)); % Save the updated data to the handles structure guidata(hObject,handles); % --- Executes during object creation, after setting all properties. function capacitance_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to capacitance_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function capacitance_edit_Callback(hObject, eventdata, handles) % hObject handle to capacitance_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Update the transfer function based on the new values of R and C handles.R = str2double(get(handles.resistance_edit,'String')); handles.C = str2double(get(handles.capacitance_edit,'String')); handles.tf = tf([1],[handles.R*handles.C 1]); % Update the transfer function display set(handles.tf_edit,'String',num2str(handles.tf)); % Save the updated data to the handles structure guidata(hObject,handles); ``` 这个示例包含了一个简单的RC电路模型,包括一个传递函数和一个时域分析操作。用户可以在界面上输入电路参数,然后点击“分析”按钮进行分析操作。分析结果将显示在界面上的波形显示框中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值