VB.NET 可选参数如何工作'在幕后'?它们是否符合 CLS? [英] How Do VB.NET Optional Parameters work 'Under the hood'? Are they CLS-Compliant?
问题描述
假设我们有以下方法声明:
Let's say we have the following method declaration:
Public Function MyMethod(ByVal param1 As Integer, _
Optional ByVal param2 As Integer = 0, _
Optional ByVal param3 As Integer = 1) As Integer
Return param1 + param2 + param3
End Function
VB.NET 如何使可选参数在 CLR 范围内工作?可选参数是否符合 CLS?
How does VB.NET make the optional parameters work within the confines of the CLR? Are optional parameters CLS-Compliant?
推荐答案
有趣的是,这是通过反射器获得的反编译的 C# 代码.
Interestingly, this is the decompiled C# code, obtained via reflector.
public int MyMethod(int param1,
[Optional, DefaultParameterValue(0)] int param2,
[Optional, DefaultParameterValue(1)] int param3)
{
return ((param1 + param2) + param3);
}
注意 Optional 和 DefaultParameterValue 属性.尝试将它们放在 C# 方法中.你会发现你仍然需要向方法传递值.然而在 VB 代码中,它变成了 Default!话虽如此,我个人从未在 VB 代码中使用过 Default.感觉就像一个黑客.方法重载对我有用.
Notice the Optional and DefaultParameterValue attributes. Try putting them in C# methods. You will find that you are still required to pass values to the method. In VB code however, its turned into Default! That being said, I personally have never use Default even in VB code. It feels like a hack. Method overloading does the trick for me.
不过,在处理 Excel Interop 时,默认确实有帮助,这在 C# 中直接使用开箱即用是一件很痛苦的事情.
Default does help though, when dealing with the Excel Interop, which is a pain in the ass to use straight out of the box in C#.
这篇关于VB.NET 可选参数如何工作'在幕后'?它们是否符合 CLS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!