我想创建一个名称列表并将其作为强类型枚举访问。例如。
string foo = FileName.Hello; //Returns "Hello.txt"
string foo1 = FileName.Bye; //Returns "GoodBye.doc"
或者它可能是一个像这样的对象:
Person p = PeopleList.Bill; //p.FirstName = "Bill", p.LastName = "Jobs"
如何创建这样的数据类型?
答案 0 :(得分:6)
虽然问题很奇怪或没有完全解释,但这是文字解决方案:
选项1:
public static class FileName
{
public const string Hello = "Hello.txt";
public const string GoodBye= "GoodBye.doc";
}
选项2:
public class Person
{
public string FirstName {get; set; }
public string LastName {get; set; }
public Person(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
}
public static class PeopleList
{
public static Person Bill = new Person("Bill", "Jobs");
}
答案 1 :(得分:5)
只需使用Dictionary<People, Person>
:
enum People { Bill, Bob};
var myDict = new Dictionary<People, Person>();
myDict.Add(People.Bill, new Person() { FirstName = "Bill", LastName = "Jobs" });
现在你可以用这种语法让Bill回来了:
Person p = myDict[People.Bill];
答案 2 :(得分:5)
您可以在Enum对象上使用扩展方法返回特定值。
看看:
http://pietschsoft.com/post/2008/07/C-Enhance-Enums-using-Extension-Methods.aspx
答案 3 :(得分:2)
Here's an article将向您展示如何创建一个属性,您可以将该属性应用于每个枚举成员,以便为其提供一些“额外”数据(在本例中为您的文件名),您可以在其他地方使用代码。
答案 4 :(得分:2)
答案 5 :(得分:2)
您可以将静态类与值一起使用..
public static class PeopleList
{
public static readonly Person Bill = new Person("Bill", "Jobs");
public static readonly Person Joe = new Person("Joe", "Doe");
}
public static class FileNames
{
public static readonly string Hello = "Hello.txt";
public static readonly string Bye = "Byte.txt";
}
然后您可以将其引用为PeopleList.Bill
或FileNames.Hello
。它不具有与枚举相同的属性,您的方法需要将字符串或Person作为参数。
答案 6 :(得分:0)
这是使用第二个示例的属性的顶级解决方案。请注意,此代码存在很多问题,仅作为示例。
public static T GetValue<T>(this Enum e) where T:class
{
FieldInfo fi = e.GetType().GetField(e.ToString());
var valueAttribute = fi.GetCustomAttributes(typeof (ValueAttribute),
false).FirstOrDefault() as ValueAttribute;
if (valueAttribute != null) return valueAttribute.Value as T;
return null;
}
class PersonValueAttribute : ValueAttribute
{
public PersonValueAttribute(string firstName, string lastName)
{
base.Value = new Person {FirstName = firstName, LastName = lastName};
}
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public static implicit operator Person(Enum e)
{
return e.GetValue<Person>();
}
}
enum PeopleList
{
[PersonValue("Steve", "Jobs")]
Steve
}
允许简单使用:
Person steve = PeopleList.Steve;
Console.WriteLine(steve.FirstName); //Steve
答案 7 :(得分:0)
我会使用Description属性将自定义数据附加到枚举。然后,您可以使用此方法返回描述的值:
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
string description = (attributes.Length > 0) ? attributes[0].Description : string.Empty;
return description;
}