C#でリフレクションを使用してフィールドの属性を取得する
-
07-07-2019 - |
質問
このようにオブジェクトからフィールドを抽出するメソッドを書きました:
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;
}
クラスの各フィールドにも独自の属性があります。この場合、私の属性はHTMLAttributesと呼ばれます。 foreachループ内で、各フィールドの属性とそれぞれの値を取得しようとしています。現在は次のようになっています。
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;
}
私の属性クラスは次のようになります:
[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();
}
}
これは論理的に思えますが、コンパイルされません。GetHTMLAttributes()メソッドに以下の赤い波線があります:
field.GetCustomAttributes(typeof(HTMLAttributes), false);
属性を抽出しようとしているフィールドは、次のように使用される別のクラスにあります:
[HTMLAttributes("input", "text")]
public string CustomerName;
私の理解(またはその欠如)から、これはうまくいくはずですか?開発者仲間の開発者を拡大してください!
*編集、コンパイラエラー:
暗黙的に型を変換することはできません 「object []」から「data.HTMLAttributes []」へ。 明示的な変換が存在します(あなたは キャストがありませんか?)
このようにキャストしようとしました:
(HTMLAttributes)field.GetCustomAttributes(typeof(HTMLAttributes), false);
しかし、これも機能しません。次のコンパイラエラーが発生します。
タイプ 'object []'を変換できません 'data.HTMLAttributes'
解決
GetCustomAttributes
メソッドは、 HTMLAttributes []
ではなく、 object []
を返します。 object []
を返す理由は、.NETジェネリックが日の目を見る前に1.0から存在していたためです。
戻り値の各アイテムを HTMLAttributes
に手動でキャストする必要があります。
コードを修正するには、次の行を変更するだけです:
object[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);
foreach
がキャストを処理します。
更新:
返される配列を HTMLAttributes []
にキャストするしない。戻り値は HTMLAttributes []
ではありません。これは、 HTMLAttributes
タイプの要素を含む object []
です。 HTMLAttribute []
型付きオブジェクト(この特定のコードスニペットでは必要ない、 foreach
で十分です)が必要な場合は、配列の各要素を個別にキャストする必要があります HTMLAttribute
;おそらくLINQを使用:
HTMLAttributes[] htmlAttributes = returnValue.Cast<HTMLAttributes>().ToArray();