【发布时间】:2012-09-14 20:58:25
【问题描述】:
我使用反射来更新已对其进行更新并保存到 mongodb 的对象
private void updateSelf(MongoDoc newDoc)
{
Type type = this.GetType();
foreach (var i in type.GetProperties())
{
if (i.GetCustomAttributes(false).Any(x => x is MongoDB.Bson.Serialization.Attributes.BsonIgnoreAttribute)) continue;
Object oldValue = i.GetValue(this, null);
Object newValue = i.GetValue(newDoc, null);
if (!Object.Equals(oldValue, newValue) && !((oldValue == null) && (newValue == null)))
{
i.SetValue(this, newValue, null);
}
}
}
这在大多数情况下都有效,但 i.SetValue(this, newValue, null); 在尝试更新此属性时会引发异常:
public uint Revision { get; private set; }
这是试图更新Product 类型的对象,它是MongoDoc 的派生类型,其中包含导致异常public uint Revision { get; private set; } 的属性Property set Method not found 我不确定是什么原因造成的,因为它适用于我的所有其他属性,只是这个抛出和异常。非常感谢任何帮助
更新:
我已经尝试过以下答案:
i.SetValue(this, newValue, System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, null, null, null);
但不幸的是完全相同的结果,它仍然会在 Revision 属性上引发异常。
更新:
例外:
System.ArgumentException was unhandled
Message=Property set method not found.
Source=mscorlib
StackTrace:
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
at Flo.Client.Docs.MongoDoc.updateSelf(MongoDoc newDoc) in F:\Flo\Flo.Client\Docs\MongoDoc.cs:line 162
at Flo.Client.Docs.MongoDoc.UpdateToMongo(MongoDoc newDoc) in F:\Flo\Flo.Client\Docs\MongoDoc.cs:line 120
at Flo.Client.Docs.Product.EditProduct(String Name, Nullable`1 State) in F:\Flo\Flo.Client\Docs\Product.cs:line 89
at Flo.Client.Program.Main() in F:\Flo\Flo.Client\Program.cs:line 26
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
【问题讨论】:
-
您的属性是否都有
private set访问器? -
是的,这让我感到困惑,我想“哦,也许是因为属性集访问器是私有的”,但是我的其他属性也有私有集访问器,而且它们被写入就好了,我读了一些该反射不关心属性访问器级别,只要属性本身是公共的,它就可以访问它。
-
Revision属性是Product类还是MongoDoc类? -
MongoDoc 类,这就是我在问题中试图说的,但不是很清楚抱歉。但是 updateSelf 方法在 MongoDoc 类中,参数是一个 mongoDoc,
this显然 -
不需要什么特别的。究竟是什么异常?包括 InnerException。
标签: c# reflection