[英]C# generic enum cast to specific enum
我有接受"T" type
通用方法,这是枚举器。 在方法内部,我必须在枚举器类型上调用辅助类方法和方法名称depands。
public Meth<T> (T type) {
if (typeof(T) == typeof(FirstEnumType)) {
FirstEnumType t = ??? // I somehow need to convert T type to FirstEnumType
this.helperFirstCalcBll(t);
}
else
{
SecondEnumType t = ??? // I somehow need to convert T type to SecondEnumType
this.helperSecondCalcBll(t);
}
}
从任意类型到枚举类型没有有效的强制转换,因此不允许这样做。 你需要先抛出对象:
FirstEnumType t = (FirstEnumType)(object)type;
这通过向上转换到object
(始终有效)来“欺骗”编译器,然后向下转换为枚举类型。 假设您已完成运行时类型检查,则向下转换将永远不会失败。 但是,在给出的else分支中实现它并不能保证工作。
有人会质疑为什么这个方法首先是通用的,但这就是你如何使这个特定的方法起作用。
public void Meth(FirstEnumType type) {
this.helperFirstCalcBll(type);
}
public void Meth(SecondEnumType type) {
this.helperSecondCalcBll(type);
}
这是dynamic
东西非常有用:
public void Meth<T>(T enumValue) where T : struct
{
InternalMeth((dynamic)enumValue);
}
private void InternalMeth(FirstEnumType enumValue)
{
this.helperFirstCalcBll(enumValue);
}
private void InternalMeth(SecondEnumType enumValue)
{
this.helperSecondCalcBll(enumValue);
}
private void InternalMeth(object enumValue)
{
// Do whatever fallback you need
}
这避免了必须编写所有if (typeof(T) == typeof(...))
和所有内容 - 你让动态调度处理器在运行时选择最佳重载。 如果所有其他的都失败,则会出现object
重载,因此您可以例如抛出异常。
尝试定义一个辅助方法:
private TOutput Convert<TInput, TOutput>(TInput value)
where TInput : struct
where TOutput : struct
{
var matchingValues = Enum.GetValues(typeof(TOutput))
.Cast<int>()
.Where(v => System.Convert.ToInt32(value) == v);
if(!matchingValues.Any())
{
var message = String.Format("No matching value found in enum '{0}' for value '{1}'.", typeof(TOutput).Name, value);
throw new ArgumentException(message);
}
var obj = (object)matchingValues.Single();
return (TOutput)obj;
}
这将转换两个枚举的值,因为输出枚举中的值等于输入值。
在您的代码中,您可以按如下方式调用它:
public Meth<T> (T type)
{
if (typeof(T) == typeof(FirstEnumType))
{
FirstEnumType t = Convert(type);
this.helperFirstCalcBll(t);
}
else
{
SecondEnumType t = Convert(type);
this.helperSecondCalcBll(t);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.