gpt4 book ai didi

c# - 如何在没有自己的构造函数的情况下在基类型的函数中调用泛型类型的构造函数?

转载 作者:行者123 更新时间:2023-11-30 16:36:44 25 4
gpt4 key购买 nike

我认为测试我对泛型函数的理解的一个好方法是创建一个函数,该函数将使用从 HashAlgorithm 继承的类之一吐出哈希的十六进制表示。由于所有 HashAlgorithm 类都提供 ComputeHash,我认为这很简单。当我构造这样一个函数时。但是,我得到一个错误,因为 HashAlgorithm 本身不提供构造函数。我也找不到提供构造函数的任何类型的 HashAlgorithm 接口(interface)或子类。如果不是所有的 HashAlgorithm 类都需要支持构造函数,我是否可以对泛型类型施加一些额外的约束以确保类型提供空构造函数,或者我是否会被迫为我知道提供的每个 HashAlgorithm 类创建重载一个空的构造函数。

这是我目前所拥有的(处于非编译状态):

public static string GetHexHash<HashAlgorithmToUse>(Stream dataStreamToHash) where HashAlgorithmToUse : HashAlgorithm
{
StringBuilder Result = new StringBuilder();
byte[] ByteHash = (new HashAlgorithmToUse()).ComputeHash(dataStreamToHash);
foreach (byte HashByte in ByteHash)
{
Result.Append(HashByte.ToString("X2"));
}
return Result.ToString();
}

编辑 Matt Hamilton 的回答立即确定了它,只是使通用约束更加复杂:where HashAlgorithmToUse : HashAlgorith, new()。我什至没有意识到我可以有多个约束。在我完全理解我能用泛型做些什么之前,我肯定还有一段路要走。我想如果您对这些约束过于执着,您可以创建一个非常非通用的通用函数。

最佳答案

尝试将 new() 子句添加到通用约束的末尾:

public static string GetHexHash<HashAlgorithmToUse>(Stream dataStreamToHash)
where HashAlgorithmToUse : HashAlgorithm, new()

这告诉类型“HashAlgorithmToUse”有一个无参数(默认)构造函数。应该可以解决问题。

关于c# - 如何在没有自己的构造函数的情况下在基类型的函数中调用泛型类型的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/399202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com