使用泛型获取属性信息

时间:2012-02-02 13:17:49

标签: c# c#-4.0

实际上,我可以通过在我的OE中执行此操作来建立表字段和变量之间的关系:

public class MyOE
{
  [Column("AGE_FIELD")]
  public int ageField { get; set; }
}

我的OE课只需要使用其他课程:

[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
public class ColumnAtt : Attribute
{
  private string name;

  public string Name
  {
    get { return name; }
  }

  public ColumnAtt (string name)
  {
     this.name = name;
  }  
}

好吧,使用上面的代码,我做了一个通用方法,我需要获得“Column”值。我怎么能这样做?

这是我的方法:

public void CompareTwoObjectsAndSaveChanges<TObjectType>(TObjectType objectA, TObjectType objectB )
{
    if(objectA.GetType() == objectB.GetType())
    {
       foreach (var prop in objectA.GetType().GetProperties())
       {
           if(prop.GetValue(objectA, null) != prop.GetValue(objectB, null))
           {
               string colvalue  = "";//Here I need to get the Column value of the attribute.
               string nameOfPropertyThatChanges = prop.Name;
               string objectAValue = prop.GetValue(objectA, null).ToString();
               string objectBValue = prop.GetValue(objectB, null).ToString();

           }
       }   
    }
}

3 个答案:

答案 0 :(得分:4)

使用反射:

    private static void Main(string[] args)
    {
        MyOE zz = new MyOE { ageField = 45 };

        foreach (PropertyInfo property in zz.GetType().GetProperties())
        {
            // Gets the first attribute of type ColumnAttribute for the property
            // As you defined AllowMultiple as true, you should loop through all attributes instead.
            var attribute = property.GetCustomAttributes(false).OfType<ColumnAttribute>().FirstOrDefault();
            if (attribute != null)
            {
                Console.WriteLine(attribute.Name);    // Prints AGE_FIELD
            }
        }

        Console.ReadKey();
    }

答案 1 :(得分:2)

试试这个:

var columnAtt = prop.GetCustomAttributes(typeof(CustomAtt),true).Cast<ColumnAtt>().FirstOrDefault();

(固定)

答案 2 :(得分:2)

您需要使用反射来获取应用于对象的属性。如果您知道该属性总是ColumnAtt,那么您可以执行以下操作来获取值:

public void CompareTwoObjectsAndSaveChanges<TObjectType>(TObjectType objectA, TObjectType objectB )
{
    if(objectA.GetType() == objectB.GetType())
    {
       foreach (var prop in objectA.GetType().GetProperties())
       {
           if(prop.GetValue(objectA, null) != prop.GetValue(objectB, null))
           {
               // Get the column attribute
               ColumnAttr attr = (ColumnAttr)objectA.GetType().GetCustomAttributes(typeof(ColumnAttr), false).First();

               string colValue = attr.Name;
               string nameOfPropertyThatChanges = prop.Name;
               string objectAValue = prop.GetValue(objectA, null).ToString();
               string objectBValue = prop.GetValue(objectB, null).ToString();
           }
       }   
    }
}

这使用了GetCustomAttributes(...)方法。