名前とリフレクションによるカスタマイズされた属性の存在に基づいて、クラスの特定のフィールドの値を取得しようとしています。私のカスタム属性は次のとおりです。
[AttributeUsage (AttributeTargets.All, AllowMultiple=true)]
public sealed class ColumnAttribute : Attribute
{
internal string name = "";
internal string length = "";
internal string precision = "";
public ColumnAttribute() { }
public ColumnAttribute(String name) { this.name = name; }
public ColumnAttribute(String name, String length) { }
public ColumnAttribute(String name, String length, String precision) { }
public String Name { get { return name; } set { name = value; } }
public String Length { get { return length; } set { length = value; } }
public String Precision { get { return precision; } set { precision = value; } }
}
これを使用するサンプル クラスは次のとおりです。
class SampleEntity
{
//private int number;
public string name;
//float marks;
public virtual int Number { get; set; }
public SampleEntity() { }
public SampleEntity(int number)
{
this.Number = number;
}
public void conversation(string request, string response) { }
public void ordinary() {
Console.Write("This isn't ordinary...");
}
[ColumnAttribute (Name = "XWBCCD")]
public String XWBCCD { get; set; }
[ColumnAttribute (Name = "XWBNCD")]
public String XWBNCD { get; set; }
私はまた、異なるフィールド名を持つ別のクラスを持っています:
class SampleRepository
{
[ColumnAttribute(Name = "XWBCCD")]
public String SomeOtherFieldName { get; set; }
[ColumnAttribute(Name = "XWBNCD")]
public String XWBNCD { get; set; }
[ColumnAttribute(Name = "XWBWCD")]
public String XWBWCD { get; set; }
}
リフレクションを通じて、フィールド名ではなく属性「名前」パラメーターを一致させることで値をコピーしようとしています。問題は、リフレクション中に、フィールドに渡された getCustomAttributes() メソッドを介してそのような比較が行われないことです。この問題を解決するための私のアプローチ(これまでのところ失敗しています)は次のとおりです。最初に、objSrc(入力された最初のクラスの)とobjDesc(空の2番目のクラス)の2つのオブジェクトを渡します。
FieldInfo[] srcFields = objSrc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.IgnoreCase |BindingFlags.FlattenHierarchy);
FieldInfo[] destFields = objDest.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
次に、すべてのフィールドでリフレクションを繰り返し実行しようとしています
foreach (FieldInfo srcFld in srcFields)
{
foreach (FieldInfo destFld in destFields)
{
if (((MemberInfo)srcFld).Name.Equals(((MemberInfo)destFld).Name)){
destFld.SetValue(objDest, srcFld.GetValue(objSrc));
break;
}
object[] srcAttr = srcFld.GetCustomAttributes(true);
object[] destAttr = destFld.GetCustomAttributes(true);
if (Utils.Length(srcAttr) == 1 && Utils.Length(destAttr) == 1){
if ((srcAttr[0]).Equals(destAttr[0]) && srcFld.FieldType.Equals(destFld.FieldType))
destFld.SetValue(objDest, srcFld.GetValue(objSrc));
else
break;
}
}
}
null を返すため、GetCustomAttributes() メソッドで問題が発生します。