Pregunta

Escribí un método que extrae campos de un 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 en mi clase también tiene sus propios atributos, en este caso mi atributo se llama HTMLAttributes. Dentro del bucle foreach, estoy tratando de obtener los atributos para cada campo y sus respectivos valores. Actualmente se ve así:

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

Mi clase de atributos se ve así:

[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();
    }
}

Esto parece lógico pero no se compila, tengo una línea roja ondulada en el método GetHTMLAttributes () en:

field.GetCustomAttributes(typeof(HTMLAttributes), false);

El campo del que estoy tratando de extraer los atributos está en otra clase utilizada de esta manera:

[HTMLAttributes("input", "text")]
public string CustomerName;

Desde mi entendimiento (o falta de ella) ¿esto debería funcionar? ¡Expanda mi mente, compañeros desarrolladores!

* Editar, error del compilador :

  

No se puede convertir implícitamente el tipo   'object []' a 'data.HTMLAttributes []'.   Existe una conversión explícita (eres tú   ¿falta un yeso?)

He intentado lanzarlo así:

(HTMLAttributes)field.GetCustomAttributes(typeof(HTMLAttributes), false);

Pero eso tampoco funciona, me sale este error del compilador:

  

No se puede convertir el tipo 'objeto []' a   'data.HTMLAttributes'

¿Fue útil?

Solución

El método

GetCustomAttributes devuelve un objeto [] , no HTMLAttributes [] . La razón por la que devuelve object [] es que ha estado allí desde 1.0, antes de que los genéricos .NET vean la luz del día.

Debe convertir manualmente cada elemento en el valor de retorno a HTMLAttributes .

Para arreglar su código, simplemente necesita cambiar la línea a:

object[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);

foreach se encargará del reparto por usted.

Actualización:

Usted no debería convertir la matriz devuelta a HTMLAttributes [] . El valor de retorno no es HTMLAttributes [] . Es un objeto [] que contiene elementos de tipo HTMLAttributes . Si desea un objeto tipeado HTMLAttribute [] (que no necesita en este fragmento de código específico, foreach sería suficiente), debe convertir cada elemento de la matriz individualmente en HTMLAttribute ; quizás usando LINQ:

HTMLAttributes[] htmlAttributes = returnValue.Cast<HTMLAttributes>().ToArray();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top