Obtendo os atributos de um campo usando reflexão em C #
-
07-07-2019 - |
Pergunta
Eu escrevi um método que extrai campos de um objeto como este:
private static string GetHTMLStatic(ref Object objectX, ref List<string> ExludeFields)
{
Type objectType = objectX.GetType();
FieldInfo[] fieldInfo = objectType.GetFields();
foreach (FieldInfo field in fieldInfo)
{
if(!ExludeFields.Contains(field.Name))
{
DisplayOutput += GetHTMLAttributes(field);
}
}
return DisplayOutput;
}
Cada campo na minha classe também tem a sua própria atributos, neste caso meu atributo é chamado htmlAttributes. Dentro do loop foreach Eu estou tentando obter os atributos para cada campo e seus respectivos valores. Atualmente, parece com isso:
private static string GetHTMLAttributes(FieldInfo field)
{
string AttributeOutput = string.Empty;
HTMLAttributes[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);
foreach (HTMLAttributes fa in htmlAttributes)
{
//Do stuff with the field's attributes here.
}
return AttributeOutput;
}
Meu atributos aparência de classe como esta:
[AttributeUsage(AttributeTargets.Field,
AllowMultiple = true)]
public class HTMLAttributes : System.Attribute
{
public string fieldType;
public string inputType;
public HTMLAttributes(string fType, string iType)
{
fieldType = fType.ToString();
inputType = iType.ToString();
}
}
Isso parece lógico, mas não vai compilar, eu tenho uma linha vermelha rabiscada nas GetHTMLAttributes () método em:
field.GetCustomAttributes(typeof(HTMLAttributes), false);
O campo Eu estou tentando extrair os atributos de está em outra classe usado como este:
[HTMLAttributes("input", "text")]
public string CustomerName;
No meu entendimento (ou falta dela) isso deve funcionar? Por favor, expandir minha mente desenvolvedores companheiros!
* Editar, erro do compilador :
Não é possível converter implicitamente o tipo 'Objeto []' para 'data.HTMLAttributes []'. existe uma conversão explícita (é você faltando um elenco?)
Eu tentei convertê-lo como este:
(HTMLAttributes)field.GetCustomAttributes(typeof(HTMLAttributes), false);
Mas isso também não funcionar, eu recebo este erro do compilador:
Não é possível converter tipo 'object []' para 'data.HTMLAttributes'
Solução
método GetCustomAttributes
retorna um object[]
, não HTMLAttributes[]
. A razão ele retorna object[]
é que ele existe desde 1.0, antes de genéricos .NET ver a luz do dia.
Você deve lançar manualmente cada item no valor de retorno para HTMLAttributes
.
Para corrigir o código, você simplesmente precisa para mudar a linha para:
object[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);
foreach
vai cuidar do elenco para você.
Update:
Você não deve converter a matriz voltou a HTMLAttributes[]
. O valor de retorno não está HTMLAttributes[]
. É um object[]
contendo elementos do tipo HTMLAttributes
. Se você quer um objeto HTMLAttribute[]
digitado (que você não precisa neste trecho de código específico, foreach
seria suficiente), você deve lançar cada elemento da matriz individualmente para HTMLAttribute
; talvez usando LINQ:
HTMLAttributes[] htmlAttributes = returnValue.Cast<HTMLAttributes>().ToArray();