[英]C# Reflection - Set Property Value
I'm trying to set a property of an object in a class, but the error says Object does not match target type
. 我正在尝试在类中设置对象的属性,但错误提示
Object does not match target type
。
FieldInfo dControl = window.GetType().GetField("dControl", BindingFlags.NonPublic | BindingFlags.Instance);
if (dControl == null) { Debug.Log ("dControl is null"); return;}
Type typeDC = dControl.FieldType;
PropertyInfo inPreviewMode = typeDC.GetProperty("InPreviewMode", BindingFlags.Public | BindingFlags.Instance);
if (inPreviewMode == null) { Debug.Log ("dControl.InPreviewMode is null"); return;}
bool value = false;
inPreviewMode.SetValue(dControl, value, null);
This is the property I'm trying to access: 这是我要访问的属性:
public class DControl : TimeArea
{
public bool InPreviewMode
{
get
{
return dState.IsInPreviewMode;
}
set
{
if (cutscene != null)
{
...
}
}
dState.IsInPreviewMode = value;
}
...
}
Help is appreciated. 感谢帮助。
The first parameter of SetValue
is the instance for which to set the value on. SetValue
的第一个参数是为其设置值的实例 。 ie, it is expecting an instance of DControl
- your code passes it an instance of FieldInfo
. 即,它期望一个
DControl
实例-您的代码将其传递给FieldInfo
实例。
So you might have to get that instance via reflection: 因此,您可能必须通过反射来获取该实例:
DControl ctrl = (DControl)dControl.GetValue(window);
And then pass that to the set value 然后将其传递给设定值
inPreviewMode.SetValue(ctrl, value, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.