TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Desenvolvimento Gestor
NA
17
4.2k
Exist Enum? Return Enum Value From String/XmlEnumAttribute
Oct 2 2017 2:56 PM
Can you simplify this code but without changing ENUM?
/// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute()] public enum Velocidade { /// [System.Xml.Serialization.XmlEnumAttribute("01")] Baixa, /// [System.Xml.Serialization.XmlEnumAttribute("02")] Normal, /// [System.Xml.Serialization.XmlEnumAttribute("03")] Rapida, }
Here is to verify if exist
private
bool
EnumHasValue(Type pTipoDoEnum,
string
valorDoEnum)
{
foreach
(var val
in
Enum.GetValues(pTipoDoEnum))
{
var member = pTipoDoEnum.GetMember(val.ToString()).FirstOrDefault();
var attribute = member.GetCustomAttributes(
false
).OfType<XmlEnumAttribute>().FirstOrDefault();
if
(valorDoEnum == attribute.Name)
{
return
true
;
}
}
return
false
;
}
Now, find string and return value:
private
object
EnumFromString(Type pTipoDoEnum,
string
valorDoEnum)
{
foreach
(var val
in
Enum.GetValues(pTipoDoEnum))
{
var member = pTipoDoEnum.GetMember(val.ToString()).FirstOrDefault();
var attribute = member.GetCustomAttributes(
false
).OfType<XmlEnumAttribute>().FirstOrDefault();
if
(valorDoEnum == attribute.Name)
{
return
val;
}
}
throw
new
Exception(
"Não existe o valor "
+ Text +
" para o tipo "
+ pTipoDoEnum.ToString() +
". Utilize o método EnumHasValue antes da conversão."
);
}
this is the call:
string
text =
"02"
;
Velocidade velocidade =
new
Velocidade();
if
(EnumHasValue(
typeof
(Velocidade),text)) velocidade = (Velocidade)EnumFromString(
typeof
(Velocidade), text);
// O resultado é: "Normal"
textBox1.Text =
"O resultado é: \""
+ velocidade.ToString() +
"\""
;
Reply
Answers (
1
)
Visual studio 2010 crashes on preview of crystal reports.
In the listView changes the icon distance ?