Domanda

Ho scritto un metodo che estrae campi da un oggetto come questo:

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

Ogni campo nella mia classe ha anche i propri attributi, in questo caso il mio attributo si chiama HTMLAttributes. All'interno del ciclo foreach sto cercando di ottenere gli attributi per ciascun campo e i loro rispettivi valori. Sembra attualmente così:

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

La mia classe di attributi è simile a questa:

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

Sembra logico ma non si compila, ho una linea rossa nel metodo GetHTMLAttributes () sotto:

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

Il campo da cui sto provando a estrarre gli attributi è in un'altra classe utilizzata in questo modo:

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

Secondo la mia comprensione (o mancanza di ciò) questo dovrebbe funzionare? Per favore, espandi i miei colleghi sviluppatori!

* Modifica, errore del compilatore :

  

Impossibile convertire implicitamente il tipo   'object []' in 'data.HTMLAttributes []'.   Esiste una conversione esplicita (sei tu   manca un cast?)

Ho provato a lanciarlo in questo modo:

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

Ma anche questo non funziona, ottengo questo errore del compilatore:

  

Impossibile convertire il tipo 'oggetto []' in   'data.HTMLAttributes'

È stato utile?

Soluzione

Il metodo

GetCustomAttributes restituisce un oggetto [] , non HTMLAttributes [] . Il motivo per cui restituisce object [] è che è stato lì dalla 1.0, prima che i generici .NET vedessero la luce del giorno.

Dovresti eseguire manualmente il cast di ciascun elemento nel valore restituito in HTMLAttributes .

Per correggere il tuo codice, devi semplicemente cambiare la riga in:

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

foreach si occuperà del cast per te.

Aggiornamento:

Non dovresti eseguire il cast dell'array restituito su HTMLAttributes [] . Il valore restituito non è HTMLAttributes [] . È un oggetto [] contenente elementi di tipo HTMLAttributes . Se si desidera un oggetto tipizzato HTMLAttribute [] (che non è necessario in questo specifico frammento di codice, foreach sarebbe sufficiente), è necessario eseguire il cast di ciascun elemento dell'array singolarmente in HTMLAttribute ; forse usando LINQ:

HTMLAttributes[] htmlAttributes = returnValue.Cast<HTMLAttributes>().ToArray();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top