I'm working on a C# project, I have this method
private static Encryption_Model Enc(byte[] PlainData,byte[] Key)
{
//Some logic code here
}
the parameter Key
I want user to enter it in one of two types byte[]
or int
.
Is there any way to force user to enter the Key parameter in one of two types byte[]
or int
without using overloading ?
Massive thanks in advance.
No, overloads are meant for this. Why don't you want that?
Sure, you could add two default parameters and throw if neither or both are provided:
private static Encryption_Model Enc(byte[] plainData, byte[] keyBytes = null, int? keyInt = null)
{
if ((keyBytes == null && keyInt == null)
|| (keyBytes != null && keyInt != null))
{
throw new ArgumentException("Provide either keyBytes or keyInt");
}
}
But that's just nasty, as now your method has to go and figure out which parameter is provided and how to use either, and it doesn't give compile-time safety. This does:
private static Encryption_Model Enc(byte[] plainData, int key)
{
var keyBytes = GetBytesFromInt(key); // Probably BitConverter.GetBytes()
return Enc(plainData, keyBytes);
}
private static Encryption_Model Enc(byte[] plainData, byte[] key)
{
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.