如何显式指定传递给函数的数组参数的大小
我有一个函数接受名为 IV 的参数。无论如何,我可以明确指定参数 IV 的大小为 16 吗?
public AESCBC(byte[] key, byte[16] inputIV)
{
//blah blah
}
上面的方法当然是行不通的。是否可以?我知道我可以在函数内部检查它并抛出异常,但是它可以在函数定义中定义吗?
I have a function which accepts a parameter named IV. Is there anyway that I can explicitly specify the size of the parameter IV to be 16 ?
public AESCBC(byte[] key, byte[16] inputIV)
{
//blah blah
}
The above is of course not working. Is it possible? I know I can check it inside the function and throw an exception but can it be defined in the function definition ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上你不能。正如 Jaroslav 所说,您可以创建自己的类型 - 但除此之外,您只能抛出异常。
使用代码合同,您可以以静态检查器可以帮助的形式表达这一点with:
那么静态检查器可以在构建时告诉您是否认为您可能违反了合同。不过,这仅适用于 Visual Studio 的高级版和旗舰版。
(您仍然可以在没有静态检查器的情况下使用 VS Professional 的代码合同,但您不会获得合同。)
插件:当前代码合同章节来自 如果您想了解更多信息,《深入 C# 第二版》 可以免费下载。
You can't, basically. As Jaroslav says, you could create your own type - but other than that, you're stuck with just throwing an exception.
With Code Contracts you could express this in a form which the static checker could help with:
Then the static checker could tell you at build time if it thought you might be violating the contract. This is only available with the Premium and Ultimate editions of Visual Studio though.
(You can still use Code Contracts without the static checker with VS Professional, but you won't get the contracts.)
Plug: Currently the Code Contracts chapter from C# in Depth 2nd edition is available free to download, if you want more information.
正如您所发现的,您无法在方法声明中指定数组参数的大小。下一个最好的事情是检查大小并抛出异常:
另一种选择是创建一个包装
byte[16]
的类并将其传递。You cannot specify the size of the array parameter in the method declaration, as you have discovered. The next best thing is to check for the size and throw an exception:
Another option it to create a class that wraps
byte[16]
and pass that through.