简体   繁体   English

当泛型类型为absract,TSymmetricAlgorithm时如何在C#中使用泛型类型方法

[英]How to use generic type methods in C# when the generic type is absract, TSymmetricAlgorithm

I am trying to call this method: 我正在尝试调用此方法:

public string Decrypt5<TSymmetricAlgorithm>(string input) where TSymmetricAlgorithm : SymmetricAlgorithm, new()
    {
        var pwdBytes = Encoding.UTF8.GetBytes(_seed);
        using (TSymmetricAlgorithm sa = new TSymmetricAlgorithm())
        {
            ICryptoTransform saDec = sa.CreateDecryptor(pwdBytes, pwdBytes);

            var encBytes = Convert.FromBase64String(input);

            var resultBytes = saDec.TransformFinalBlock(encBytes, 0, encBytes.Length);
            Debug.WriteLine(Encoding.UTF8.GetString(resultBytes));
            return Encoding.UTF8.GetString(resultBytes);
        }
    }

By calling Decrypt5<TSymmetricAlgorithm>("myEncryptedStringBlahblahxyz"); 通过调用Decrypt5<TSymmetricAlgorithm>("myEncryptedStringBlahblahxyz"); But I keep getting an error that I must use a non-abstract type with a public parameter-less type instead of TSymmetricAlgorithm. 但是我不断收到一个错误,我必须使用非抽象类型和公共无参数类型而不是TSymmetricAlgorithm。 Is there a default TSymmetricAlgorithm subclass that I can use. 我可以使用默认的TSymmetricAlgorithm子类吗? What am I doing wrong? 我究竟做错了什么? Thank you. 谢谢。

Turns out using RijndaelManaged object type did the trick. 原来使用RijndaelManaged对象类型可以解决问题。 I found this out through trial and error. 我通过反复试验发现了这一点。 If anyone knows a fast way to find out all the native classes in C# that subclass a certain parent abstract class (SymmetricAlgorithm in this case), please feel free to let me know in comments for future reference. 如果有人知道一种快速的方法来找出C#中所有子类(该类是某个父抽象类)的子类(在本例中为SymmetricAlgorithm),请随时在注释中告知我以备将来参考。 I'm new to C# :-) 我是C#的新手:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM