是否可以这样做:
public static T ToEnum<T>(this string s, Type T)
{
return (T)Enum.Parse(typeof(T), s);
}
或者以其他方式,即使用参数 T 作为返回类型?
最佳答案
你可以这样做
public static class Extensions
{
public static T ToEnum<T>(this string s) where T : struct
{
return (T)Enum.Parse(typeof(T), s);
}
}
public enum TestEnum
{
None,
Special,
}
class Program
{
static void Main(string[] args)
{
var x = TestEnum.Special.ToString();
var y = x.ToEnum<TestEnum>(); // y will be TestEnum.Special
}
}
关于c# - 使用 Type 参数作为返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8223959/