使用泛型获取属性信息 [英] Get Attribute info with generics
本文介绍了使用泛型获取属性信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
实际上,我可以通过在我的OE中这样做一个表字段和变量之间的关系:
actually, I can make a relation between a table field and a variable by doing this inside my OE:
public class MyOE
{
[Column("AGE_FIELD")]
public int ageField { get; set; }
}
我的OE类只需要使用这个类:
My OE class just need to use this other class:
[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;
}
}
使用上面的代码,方法,我将需要获取列值。
Well, using the code above, Im doing a generic method that I will need to get the "Column" value. How I could do that?
这里是我的方法:
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();
}
}
}
}
推荐答案
您需要使用反射来获取应用于您的对象的属性。如果你知道属性总是 ColumnAtt
,那么你可以这样做,得到的值:
You need to use reflection to get the attributes applied to your object. If you know the attribute is always going to be ColumnAtt
, then you can do something like this to get the value:
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(...)
方法。
这篇关于使用泛型获取属性信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文