[英]Can I return the contents of an enum as a list using an extension method?
I have the following Enum: 我有以下枚举:
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");
}
}
I already created an extension method that formats the output but now I have another requirement. 我已经创建了一个格式化输出的扩展方法,但现在我有了另一个要求。 What I need to do is to create an extension method that will return the contents of the enum into a list of the following class:
我需要做的是创建一个扩展方法,将枚举的内容返回到以下类的列表中:
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
}
Is it possible to do this in an extension method? 是否可以在扩展方法中执行此操作?
Try the following: 请尝试以下方法:
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();
}
If you want to create an instance of the Reference
-class for just one element in an extenstion method try this: 如果要在扩展方法中仅为一个元素创建
Reference
-class的实例,请尝试以下操作:
public static Reference ToReference(this QuestionType questionType)
{
return new Reference
{
PartitionKey = "00",
RowKey = (int)questionType,
Value = questionType.ToString()
};
}
How about... 怎么样...
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()});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.