Я хочу ограничить параметры универсального типа определенным набором интерфейсов и их реализаторами и/или классами и их унаследованными дочерними классами.
В моем конкретном случае мне нужны параметры типов 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
Как ограничить параметры универсального типа набором классов? ⇐ C#
Место общения программистов C#
-
Anonymous
1769938842
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;
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79880275/how-to-restrict-generic-type-parameters-to-a-set-of-classes[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия