Самое простое решение - создать функцию JavaScript и вызвать его для обратного вызова Ajax success
.
function callServerAsync(){
$.ajax({
url: '...',
success: function(response) {
successCallback(response);
}
});
}
function successCallback(responseObj){
// Do something like read the response and show data
alert(JSON.stringify(responseObj)); // Only applicable to JSON response
}
function foo(callback) {
$.ajax({
url: '...',
success: function(response) {
return callback(null, response);
}
});
}
var result = foo(function(err, result){
if (!err)
console.log(result);
});
Вы должны написать свой собственный обратный метод. Метод parse (), очевидно, не знает о ваших атрибутах описания.
Что-то вроде этого должно работать:
public static T GetEnumValueFromDescription<T>(string description)
{
MemberInfo[] fis = typeof(T).GetFields();
foreach (var fi in fis)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0 && attributes[0].Description == description)
return (T)Enum.Parse(typeof(T), fi.Name);
}
throw new Exception("Not found");
}
Вам нужно найти лучшее, что можно сделать чем выбросить исключение, если значение перечисления не было найдено. :) [/ Д2]
Этот ответ на соответствующий вопрос показывает, как получить атрибуты для данного типа. Вы можете использовать аналогичный подход для сравнения данной строки с атрибутами описания Enum
.
static string GetEnumDescription<T>(T value) {
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false
);
if (attributes != null &&
attributes.Length > 0) {
return attributes[0].Description;
}
else {
return value.ToString();
}
}
static T ParseDescriptionToEnum<T>(string description) {
Array array = Enum.GetValues(typeof(T));
var list = new List<T>(array.Length);
for(int i = 0; i < array.Length; i++) {
list.Add((T)array.GetValue(i));
}
var dict = list.Select(v => new {
Value = v,
Description = GetEnumDescription(v) }
)
.ToDictionary(x => x.Description, x => x.Value);
return dict[description];
}
Я не делал попыток проверки ошибок. Обратите внимание, что словарь не нужно создавать при каждом вызове метода, но я слишком ленив, чтобы исправить это.
Использование:
enum SomeEnum {
[Description("First Value")]
FirstValue,
SecondValue
}
SomeEnum value = ParseDescriptionToEnum<SomeEnum>("First Value");
Тест, который проходит:
[Fact]
public void Can_parse_a_value_with_a_description_to_an_enum() {
string description = "First Value";
SomeEnum value = ParseDescriptionToEnum<SomeEnum>(description);
Assert.Equal(SomeEnum.FirstValue, value);
}
[Fact]
public void Can_parse_a_value_without_a_description_to_an_enum() {
string description = "SecondValue";
SomeEnum value = ParseDescriptionToEnum<SomeEnum>(description);
Assert.Equal(SomeEnum.SecondValue, value);
}
Для этого вы также можете использовать Humanizer . Чтобы получить описание, которое вы пишете:
EAssemblyUnit.eUCAL1.Humanize();
и чтобы получить перечисление из описания, которое вы хотите, вы можете написать:
"UCAL1".DehumanizeTo<EAssemblyUnit>();
Отказ от ответственности: I Я - создатель Гуманизатора.
Я бы поддержал ответ Анны, но у меня нет такой репутации. С частью этого, основанного на ее ответе, это двухстороннее решение, с которым я столкнулся. Поставка метода defaultValue в ParseEnum охватывает случаи, когда один и тот же Enum может иметь разные значения по умолчанию, используя его.
public static string GetDescription<T>(this object enumerationValue) where T : struct
{
// throw an exception if enumerationValue is not an Enum
Type type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}
//Tries to find a DescriptionAttribute for a potential friendly name for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
//Pull out the description value
return attributes[0].Description;
}
}
//In case we have no description attribute, we'll just return the ToString of the enum
return enumerationValue.ToString();
}
public static T ParseEnum<T>(this string stringValue, T defaultValue)
{
// throw an exception if T is not an Enum
Type type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException("T must be of Enum type", "T");
}
//Tries to find a DescriptionAttribute for a potential friendly name for the enum
MemberInfo[] fields = type.GetFields();
foreach (var field in fields)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0 && attributes[0].Description == stringValue)
{
return (T)Enum.Parse(typeof(T), field.Name);
}
}
//In case we couldn't find a matching description attribute, we'll just return the defaultValue that we provided
return defaultValue;
}