gpt4 book ai didi

c# - 第二个参数取决于第一个参数的通用函数

转载 作者:太空狗 更新时间:2023-10-30 00:53:08 25 4
gpt4 key购买 nike

是否有可能在 C# 中创建一个通用函数,其中第一个参数是一个枚举(我猜是几个中的一个,所以它必须是通用的)并且第二个参数被强制为选为第一个的枚举中的值范围?我知道必须使用泛型,但我想不出如何编写这样的表达式,或者是否可能。

编辑:添加代码示例我知道这个代码示例不起作用,但它在我的思考方向上说明了一点。

public List<int> Call<EnumValue>(Type enumType, EnumValue enumValue) where EnumValue : Enum.GetValues(typeof(enumType))
{
// Something
}

最佳答案

我认为不可能有这样的编译时约束。您能做的最好的事情就是运行时检查:

public List<int> Call<TEnum>(Type enumType, TEnum enumValue) 
{
if(!enumType.IsAssignableFrom(typeof(TEnum)))
throw new ArgumentException();

// Something
}

更新:虽然我不确定您为什么需要传递类型,但如果它必须与另一个类型相同无论如何参数。不能去掉第一个参数吗?

public List<int> Call<TEnum>(TEnum enumValue) 
{
Type enumType = typeof(TEnum);

// Something
}

关于c# - 第二个参数取决于第一个参数的通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17744077/

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