gpt4 book ai didi

c# - Reflection.TargetException问题

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

我希望 Employee 的 EmployeeNumber 属性仅由数据库设置,但我需要能够设置单元测试的值。这就是为什么我在下面制作了帮助程序代码。

有人可以帮我排查和解决这个问题吗?

干杯,
贝瑞尔

助手代码

public static void SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
{
var empNumberProperty = employee.GetType().GetProperty("EmployeeNumber", BindingFlags.Public | BindingFlags.Instance);

Check.Invariant(empNumberProperty != null);
Check.Invariant(empNumberProperty.PropertyType.Equals(typeof(EmployeeNumber)));

empNumberProperty.SetValue(empNumberProperty, employeeNumber, null);
}

完全异常

System.Reflection.TargetException : Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
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)
TestableEmployee.cs(36,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelper.SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
TestableEmployee.cs(47,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelperTests.SetEmployeeNumberFor()

EmployeeNumber 属性代码

    public virtual EmployeeNumber EmployeeNumber {
get { return _employeeNumber; }
protected set {
_employeeNumber = value;
//base.BusinessId = _employeeNumber;
}
}
private EmployeeNumber _employeeNumber;

最佳答案

试试用这个代替:

empNumberProperty.SetValue(employee, employeeNumber, null);

问题是 SetValue 的第一个参数是您尝试修改的对象。

同时查看 MSDN Documentation ,我还注意到,如果“非法尝试访问类中的私有(private)或 protected 方法”,此方法可能会抛出 MethodAccessException,这似乎适用于这种情况。在备注部分,出现此通知:

Starting with the .NET Framework version 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller’s grant set, or a subset thereof. To use this functionality, your application should target the .NET Framework version 3.5 or later.

或者,您可以尝试使用 GetSetMethod(bool) ,但这仍将受到相同的安全限制。

empNumberProperty.GetSetMethod(true).Invoke(employee, new[] { employeeNumber });

关于c# - Reflection.TargetException问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4731186/

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