0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

stringをenumに変換する便利クラス

Posted at

| 概要

よく使うし、Extensionで実装することが多かったので
このスクリプトだけ入れておけばOKなものを作った。
中身はTryParseしているだけのつくり。特に解説はない。

| ソースコード全文

EnumParser.cs

using System;

/// <summary>
/// Enumのパース用
/// </summary>
public static class EnumParser
{
    public static T Parse<T>(string value) where T : struct, Enum
    {
        T result;
        if (!Enum.TryParse(value, true, out result))
        {
            throw new ArgumentException($"'{value}' is not a valid value for {typeof(T).Name}.");
        }
        return result;
    }
}

| 使用例

using System;

enum WeaponType
{
    Sword,
    Spear,
    Axe,
}
void Func(string _weaponType)
{
    WeaponType weapon = EnumParser.Parse<WeaponType>(_weaponType);
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?