Is it possible in C# to create a generic function where the first parameter is an enum (one of several so it has to be generic I guess) and the second parameter is forced to be a value from the enum selected as the first parameter? I understand generics has to be used but I can't think of how to write such an expression, or if it's even possible.
Edit: Added code example I know that this code example doesn't work but it illustrates a little in the direction I was thinking.
public List<int> Call<EnumValue>(Type enumType, EnumValue enumValue) where EnumValue : Enum.GetValues(typeof(enumType))
{
// Something
}
I don't think it is possible to have a compile-time constraint like that. The best you could do is a run-time check:
public List<int> Call<TEnum>(Type enumType, TEnum enumValue)
{
if(!enumType.IsAssignableFrom(typeof(TEnum)))
throw new ArgumentException();
// Something
}
UPDATE : Although I'm not sure why you need to pass the Type
, if it has to be same type as the other parameter anyway. Couldn't you get rid of the first parameter?
public List<int> Call<TEnum>(TEnum enumValue)
{
Type enumType = typeof(TEnum);
// Something
}
我想做类似事情的唯一方法是在函数内部添加一个条件,如果参数错误(有明确的解释),则返回某些内容或引发Exception。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.