gpt4 book ai didi

c# - 使用泛型获取属性信息

转载 作者:行者123 更新时间:2023-11-30 19:30:26 31 4
gpt4 key购买 nike

实际上,我可以通过在我的 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();

}
}
}
}

最佳答案

使用反射:

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

关于c# - 使用泛型获取属性信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9113020/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com