Parsing value into nullable enumeration

末鹿安然 提交于 2021-02-18 22:24:29

问题


Let's say I have this:

PriorityType? priority;
string userInput = ...;

I cannot change how this is defined: PriorityType? priority because it's actually part of a contract with another piece of code.

I tried this, but it does not work:

if (Enum.TryParse<PriorityType?>(userInput, out priority)) {

What is the correct way?


回答1:


The simplest way:

PriorityType tempPriority;
PriorityType? priority;

if (Enum.TryParse<PriorityType>(userInput, out tempPriority))
    priority = tempPriority;

This is the best I can come up with:

public static class NullableEnum
{
    public static bool TryParse<T>(string value, out T? result) where T :struct, IConvertible
    {
        if (!typeof(T).IsEnum)
            throw new Exception("This method is only for Enums");

        T tempResult = default(T);

        if (Enum.TryParse<T>(value, out tempResult))
        {
            result = tempResult;
            return true;
        }

        result = null;
        return false;
    }
}

Use:

if (NullableEnum.TryParse<PriorityType>(userInput, out priority))

The above class can be used just like Enum.TryParse except with a nullable input. You could add another overloaded function that takes a non-nullable T so that you could use it in both instances if you want. Unfortunately extension methods don't work very well on enum types (as far as I could try to manipulate it in the short time I tried).




回答2:


If you want it to be a single line of code, you can do it like this:

var priority = Enum.TryParse<PriorityType>(userInput, out var outPriority) ? outPriority : (PriorityType?) null;



回答3:


This is the same solution posted by Ron Beyer with a little refactoring:

 public static class NullableEnum
{
    public static bool TryParse<T>(string value, out T? result) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException("Invalid Enum");

        result = Enum.TryParse(value, out T tempResult) ? tempResult : default(T?);

        return (result == null) ? false : true;
    }
}


来源:https://stackoverflow.com/questions/33311196/parsing-value-into-nullable-enumeration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!