在下面的代码中,我只是将一个字符串(例如"medium")转换为其Enum值.我需要做的不是将Opacity作为固定的Enum类型,而是将其作为参数传递,以便该函数在任何枚举上运行.这似乎证明比我预期的更困难,即'Enum MyEnum'不起作用.有人解决吗?
public enum Opacity
{
Low,
Medium,
High
}
public static Enum StringToEnum(String str)
{
return (Opacity)Enum.Parse(typeof(Opacity), str, true); // Case insensitive
}
Run Code Online (Sandbox Code Playgroud)
public static T StringToEnum<T>(String str) where T : struct
{
return (T)Enum.Parse(typeof(T), str, true);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |