函数调用约束

Dun*_*oud 1 .net c# asp.net

是否有类似C#的"调用约束"?

例如,我有以下功能:

public UInt16 ConvertByteToUInt16 (byte[] buffer)
{
   if (buffer.Length != 2)
   {
       throw new InvalidArgumentException(); 
   }

   Convert();
}
Run Code Online (Sandbox Code Playgroud)

有可能写出类似的东西:

public UInt16 ConvertByteToUInt16 (byte[] buffer) : where (buffer.Lenght = 2)
{
    Convert();       
}
Run Code Online (Sandbox Code Playgroud)

如果我这样调用函数:

ConvertByteToUInt16 (new byte[] { 0xFF, 0xFF, 0xFF } )
Run Code Online (Sandbox Code Playgroud)

我想在编译时遇到错误.我很确定C#2.0上没有这样的东西,但也许在C#4.0上?提前致谢.

the*_*oop 5

您无法在标准.NET中执行此操作.您需要手动检查,然后抛出一个适当的异常:

public UInt16 ConvertByteToUInt16 (byte[] buffer)
{
    if (buffer.Length != 2)
        throw new ArgumentException("buffer needs to be of length 2", "buffer");
    Convert();       
}    
Run Code Online (Sandbox Code Playgroud)