我有个像这样的东西
oldEntity
Active: true
ActiveDirectoryName: ""
ArchiveConceptValueList: null
AsgScndCnpRangeDictionary: Count = 0
AssignedRuleList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedRule>}
AssignedScndCnpRangeList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedScndCnpRange>}
AssignedScndCnpRangePeresentList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedScndCnpRange>}
AssignedWGDShiftList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedWGDShift>}
AssignedWorkGroupList: {GTS.Clock.Model.PersonWorkGroup, GTS.Clock.Model.PersonWorkGroup}
Assistant: null
BarCode: "0451343786"
BasicTrafficController: {GTS.Clock.Model.Concepts.BasicTrafficController}
BasicTrafficList: {}
BudgetList: null
CFPNeedUpdate: false
CalcDateZone: null
CardNum: "2465"
CartOrgan: {GTS.Clock.Model.Charts.Department}
CheckEnterAndExitInRequest: false
CostCenter: {GTS.Clock.Model.BaseInformation.CostCenter}
CurrentActiveContract: null
CurrentActiveDateRangeGroup: null
CurrentActiveRuleGroup: null
CurrentActiveWorkGroup: null
CurrentRangeAssignment: null
CurrentYearBudgetList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.Concepts.CurrentYearBudget>}
DelayCartableList: {}
Department: {GTS.Clock.Model.Charts.Department}
DepartmentID: 0
...我要一个叫fiel的部门。除了oldEntity这样的部门:

部门字段的属性如下:

一旦我使用下面的代码获得带有反射的部门名称字段,我就得到了这个erro
oldEntity.GetType().GetProperty("Department").GetValue("Name", null);对象不匹配目标类型.
发布于 2022-01-03 09:20:30
您试图获取属性的值,就好像它是string的属性一样-- GetValue的第一个参数需要是从其中获取属性的对象(在本例中是oldEntity)。这样你就能得到这样的部门:
object department = oldEntity.GetType().GetProperty("Department").GetValue(oldEntity, null);要获得Name属性(我希望它是一个属性而不是一个公共字段),您需要再次执行相同的操作:
object name = department.GetType().GetProperty("Name").GetValue(department, null);但是,您可以更简单地使用动态类型来完成这一切:
dynamic entity = oldEntity;
string name = entity.Department.Name;注意,对于Department或Name部件没有编译时检查(或者结果类型是string),但这与基于反射的代码是相同的。动态输入只会在执行时为您执行反射。
https://stackoverflow.com/questions/70563618
复制相似问题