Well, the attribute itself cannot take that form, but you could use an
attribute to do this; the following is not very optimised (you could
cache the pairs in a static list/dictionary) - but works for
illustration:
Marc
using System;
using System.Reflection;
static class Program
{
static void Main()
{
ContentTypes ct = ContentTypes.UrlEncoded;
string mime = ContentType.GetMime(ct);
ContentTypes parsed = ContentType.Parse(mime);
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false,
Inherited = true)]
public sealed class MimeAttribute : Attribute
{
public MimeAttribute(string contentType)
{
ContentType = contentType;
}
public string ContentType { get; private set; }
}
public enum ContentTypes
{
[Mime(@"text/xml")]
Xml,
[Mime(@"application/x-www-form-urlencoded")]
UrlEncoded
}
static class ContentType
{
public static ContentTypes Parse(string mime)
{
foreach (FieldInfo field in typeof(ContentTypes).GetFields())
{
MimeAttribute attrib = Attribute.GetCustomAttribute(field,
typeof(MimeAttribute))
as MimeAttribute;
if (attrib != null && attrib.ContentType == mime)
{
return (ContentTypes) field.GetValue(null);
}
}
throw new ArgumentException("mime");
}
public static string GetMime(ContentTypes contentType)
{
FieldInfo field =
typeof(ContentTypes).GetField(contentType.ToString());
if (field != null)
{
MimeAttribute attrib = Attribute.GetCustomAttribute(field,
typeof(MimeAttribute))
as MimeAttribute;
if (attrib != null) return attrib.ContentType;
}
throw new ArgumentException("contentType");
}
}