Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 类是否可以通过反射访问从它继承的类中的字段?_C#_Reflection - Fatal编程技术网

C# 类是否可以通过反射访问从它继承的类中的字段?

C# 类是否可以通过反射访问从它继承的类中的字段?,c#,reflection,C#,Reflection,我想做的是有一个类,我可以从中继承,并能够跟踪对属性的更改 我有一个叫做TrackedEntity的基类 然后,我创建了另一个从TrackedEntity继承的类TestEntity 在我的TestEntity类中,我用一个名为CompareValues的属性标记了一个字段 轨迹性 公共类跟踪属性{ public void GetCompareValues(){ var类型=类型(T); var properties=type.GetProperties(); foreach(属性中的var属性

我想做的是有一个类,我可以从中继承,并能够跟踪对属性的更改

我有一个叫做TrackedEntity的基类

然后,我创建了另一个从TrackedEntity继承的类TestEntity

在我的TestEntity类中,我用一个名为CompareValues的属性标记了一个字段

轨迹性

公共类跟踪属性{
public void GetCompareValues(){
var类型=类型(T);
var properties=type.GetProperties();
foreach(属性中的var属性){
var attribute=(CompareValues[])property.GetCustomAttributes
(typeof(CompareValues),false);
var hasAttribute=Attribute.IsDefined(属性,类型
(比较值);
}
}
}
测试性

公共类测试实体:TrackedEntity
{
公共int one{get;set;}
[比较值]
公共整数二{get;set;}
公共整数三{get;set;}
}
CompareValues属性:

[AttributeUsage(AttributeTargets.Property |
属性。字段,
继承的(正确)]
公共类CompareValues:属性{
公共比较值(){}
}
我可以这样做

var test=newtestentity();
test.GetCompareValues();
在我的GetCompareValues方法中,我可以找到TestEntity中哪些字段使用了我的CompareValues属性

我试图找到一种方法来访问具有CompareValues属性的字段的值,以便跟踪更改并记录有关更改的信息

如果有任何其他方法可以通过使用其他方法来完成,请让我知道


谢谢。

你就快到了。您所需要做的就是获取当前实例上的属性值—您调用该方法的实例:

if(hasAttribute)
{
    var value = property.GetValue(this, null);
}
除此之外,这里不需要泛型。只要用这个:

var type = this.GetType();

如果实例是派生类型,则返回
TestEntity

GetType()
返回对象的实际运行时类型,即使在引用基类时调用它也是如此。否则就没什么意义了。你的问题写得不太清楚。你的标题说你想获取字段,但是你发布的代码涉及属性。无论如何,获取特定对象的字段或属性是一个众所周知的、有文档记录的操作,与此相关的问题在堆栈溢出时已经被回答了数百次。有关示例,请参见标记的副本。对此表示抱歉!非常感谢你!