Как ограничить параметры универсального типа набором классов?C#

Место общения программистов C#
Ответить
Anonymous
 Как ограничить параметры универсального типа набором классов?

Сообщение Anonymous »

Я хочу ограничить параметры универсального типа определенным набором интерфейсов и их реализаторами и/или классами и их унаследованными дочерними классами.
В моем конкретном случае мне нужны параметры типов TIn и TRet для этих методов:
TRet EncrpytT(TIn tinSource, ...)
TRet DecrpytT(TIn tinSource, ...)

может иметь только следующие типы:
string, char[], byte[], IEnumerable, IEnumerable
// includes also List HashSet, ...

Возможно ли это с помощью следующего предложения:
where TRet : { IEnumerable, String, byte[], char[], IEnumerable }, TIn : { IEnumerable, String, byte[], char[], IEnumerable }

Я обнаружил только, что вы можете ограничить типы в предложенииwhere одним интерфейсом и всеми разработчиками или одним классом и всеми унаследованными классами, например
where TRet : IEnumerable, TIn : IEnumerable

Вот конкретный пример, который я не смог написать достаточно хорошо:
///
/// DecrpytT generic decryption method
///
/// return type
///
///
///
///
///
/// encrypted message
/// Unique deterministic user key to encrypt
/// unique key for each symmetric cipher algorithm in each stage of pipe
/// type for encoding encrypted bytes back in ascii-7 plain text>
/// and
/// key hashing algorithm
///
/// Decrypted generic TRet
public static TRet DecrpytT(TIn tinSource,
string cryptKey, string hashIv,
EncodingType decoding = EncodingType.Base64,
ZipType unzipAfter = ZipType.None,
KeyHash keyHash = KeyHash.Hex, CipherMode cmode = CipherMode.ECB)
{
hashIv = hashIv ?? keyHash.Hash(cryptKey);
byte[] stringBytes = new List().ToArray();
// create symmetric cipher pipe for decryption with crypt key and pass pipeString as out param
SymmCipherPipe symmPipe = new SymmCipherPipe(cryptKey, hashIv, decoding, unzipAfter, keyHash, cmode, true);

string incomingEncoded = string.Empty;
if (tinSource is string inString)
incomingEncoded = inString;
else if (tinSource is char[] chars)
incomingEncoded = chars.ToString();
else if (tinSource is IEnumerable charsIEnumerable)
incomingEncoded = new string(charsIEnumerable.ToArray());
else if (tinSource is byte[] inBytes)
incomingEncoded = System.Text.Encoding.UTF8.GetString(inBytes);
else if (tinSource is IEnumerable bytesEnumerable)
incomingEncoded = System.Text.Encoding.UTF8.GetString(bytesEnumerable.ToArray());
else throw new CException($"Unknown Type Exception, type {typeof(TIn)} is not supported.");

// get bytes from encrypted encoded string dependent on the encoding type (uu, base64, base32,..)
byte[] cipherBytes = decoding.GetEnCoder().Decode(incomingEncoded);
// staged decryption of bytes
byte[] intermediatBytes = symmPipe.DecrpytRoundGoMerry(cipherBytes, cryptKey, hashIv, cmode);
// Unzip after if necessary
byte[] decryptedBytes = (unzipAfter != ZipType.None) ? unzipAfter.Unzip(intermediatBytes) : intermediatBytes;

TRet result = default(TRet);
if (typeof(TRet) == typeof(string))
result = (TRet)(object)System.Text.Encoding.UTF8.GetString(decryptedBytes);
else if (typeof(TRet) == typeof(char[]))
result = (TRet)(object)System.Text.Encoding.UTF8.GetString(decryptedBytes).ToCharArray();
else if (typeof(TRet) == typeof(IEnumerable))
result = (TRet)(object)System.Text.Encoding.UTF8.GetString(decryptedBytes).ToCharArray();
else if (typeof(TRet) == typeof(byte[]))
result = (TRet)(object)decryptedBytes;
else if (result is IEnumerable bytesIEnumerable)
result = (TRet)(object)decryptedBytes;
else throw new CException($"Unknown Type Exception, type {typeof(TRet)} is not supported.");

return result;
}


Подробнее здесь: https://stackoverflow.com/questions/798 ... of-classes
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»