1
私は基本的にint型と文字列のdictionayに列挙型を回す私のコードでは、次の2つの方法があります。これらの2つの方法のコードは基本的に同じであるので一般的な列挙型メソッドを作成するには?
public Dictionary<int, string> GetChannelLevels()
{
IEnumerable<ChannelLevel> enumValues = Enum.GetValues(typeof(ChannelLevel)).Cast<ChannelLevel>();
var channelLevels = enumValues.ToDictionary(value => (int)value, value => value.ToString());
return channelLevels;
}
public Dictionary<int, string> GetCategoryLevels()
{
IEnumerable<CategoryLevel> enumValues = Enum.GetValues(typeof(CategoryLevel)).Cast<CategoryLevel>();
var channelLevels = enumValues.ToDictionary(value => (int)value, value => value.ToString());
return channelLevels;
}
を、私は一般的な方法を書いて考えますこれは次のようになります:
private Dictionary<int, string> GetEnumDictionary<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
IEnumerable<T> enumValues = Enum.GetValues(typeof(T)).Cast<T>();
var channelLevels = enumValues.ToDictionary(value => /*THIS IS WHERE THE PROBLEM IS*/ (int)value, value => value.ToString());
return channelLevels;
}
問題は、C#は、一般的な列挙型を持っていないので、することは列挙型としてTを認識望めない方法をconstaintsので、私はconveryでintに望めないということです。
新しい機能をすべて記述することなくこの問題を解決するにはどうすればよいですか?
*キャスティング*を終了するときに、なぜ汎用メソッドを使用しますか?いずれの場合でも、すべての列挙型は[System.Enum](https://docs.microsoft.com/en-us/dotnet/api/system.enum?view=netframework-4.7.1)型のインスタンスです。 –
可能な重複[Enum to Dictionary c#](https://stackoverflow.com/questions/5583717/enum-to-dictionary-c-sharp) –
@JamesThorpeのリンクに感謝します。私はそのような機能を実装することで問題を解決できると思う。 –