1

我有以下枚举:

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");
    }
}

我已经创建了一个格式化输出的扩展方法,但现在我有另一个要求。我需要做的是创建一个扩展方法,它将枚举的内容返回到以下类的列表中:

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
}

是否可以在扩展方法中做到这一点?

4

2 回答 2

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扩展方法中的一个元素创建 -class 的实例,请尝试以下操作:

public static Reference ToReference(this QuestionType questionType)
{
    return new Reference
                     {
                         PartitionKey = "00", 
                         RowKey = (int)questionType, 
                         Value = questionType.ToString()
                     };
}    
于 2012-10-23T09:02:17.993 回答
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()});
    }
} 
于 2012-10-23T09:12:53.420 回答