我有以下枚举:
public enum QuestionType {
Check = 1,
CheckAndCode = 2,
na = 99
};
public static class QuestionTypeExtension
{
public static string D2(this QuestionType key)
{
return ((int) key).ToString("D2");
}
}
我已经创建了一个格式化输出的扩展方法,但现在我有了另一个要求。我需要做的是创建一个扩展方法,将enum的内容返回到以下类的列表中:
public class Reference {
public string PartitionKey { get; set; } // set to "00"
public int RowKey { get; set; } // set to the integer value
public string Value { get; set; } // set to the text of the Enum
}
是否可以在扩展方法中执行此操作?
答案 0 :(得分:2)
尝试以下方法:
public static List<Reference> GetReferencesForQuestionType()
{
return Enum.GetValues(typeof(QuestionType))
.Cast<QuestionType>()
.Select(x => new Reference
{
PartitionKey = "00",
RowKey = (int)x,
Value = x.ToString()
})
.ToList();
}
如果要在扩展方法中仅为一个元素创建Reference
- 类的实例,请尝试以下方法:
public static Reference ToReference(this QuestionType questionType)
{
return new Reference
{
PartitionKey = "00",
RowKey = (int)questionType,
Value = questionType.ToString()
};
}
答案 1 :(得分:1)
怎么样......
public static class QuestionTypeExtension
{
public static IEnumerable<Reference> Reference()
{
return Enum.GetValues(typeof(QuestionType)).OfType<QuestionType>().
Select(qt=>new Reference(){ PartitionKey = "00", RowKey = (int)qt, Value = qt.ToString()});
}
}