C#泛型枚举转换为特定枚举

ren*_*thy 12 c# enums

我有接受的通用方法,"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);
    }    
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*ray 16

从任意类型到枚举类型没有有效的强制转换,因此不允许这样做.你需要先抛出对象:

FirstEnumType t = (FirstEnumType)(object)type;
Run Code Online (Sandbox Code Playgroud)

这通过向上转换object(通常是有效的)来"欺骗"编译器,然后向下转换为枚举类型.假设您已完成运行时类型检查,则向下转换将永远不会失败.但是,在给出的else分支中实现它并不能保证工作.

有人会质疑为什么这个方法首先是通用的,但这就是你如何使这个特定的方法起作用.

  • @atlaste这也不是一个有效的演员. (4认同)

Rob*_*Kee 5

public void Meth(FirstEnumType type) {
    this.helperFirstCalcBll(type);
}
public void Meth(SecondEnumType type) {
    this.helperSecondCalcBll(type);
}
Run Code Online (Sandbox Code Playgroud)