报错Expression of type 'System.Boolean' cannot be used for parameter of type 'System.Object' of method 'System.Object SetValue(System.String, System.Object)' (Parameter 'arg1')
时间: 2024-01-01 15:05:57 浏览: 45
这个错误通常出现在使用反射(Reflection)设置属性值时,赋值的类型和属性定义的类型不一致导致的。
可能是在使用反射设置属性值时,给属性传递了一个布尔类型的值,但是属性定义的类型不是布尔类型。这种情况下,需要将布尔类型的值转换为属性定义的类型,再使用反射设置属性值。
例如,假设有一个Person类,其中有一个int类型的Age属性:
```csharp
public class Person
{
public int Age { get; set; }
}
```
然后,假设我们使用反射设置Age属性的值:
```csharp
Person person = new Person();
PropertyInfo ageProperty = typeof(Person).GetProperty("Age");
ageProperty.SetValue(person, true);
```
在这个例子中,我们将一个布尔类型的值(true)赋值给Age属性,但是Age属性定义的类型是int类型,所以会抛出上述错误。
要解决这个问题,我们需要将布尔类型的值转换为int类型,例如:
```csharp
Person person = new Person();
PropertyInfo ageProperty = typeof(Person).GetProperty("Age");
ageProperty.SetValue(person, Convert.ToInt32(true));
```
这样就可以将布尔类型的值转换为int类型,然后成功使用反射设置Age属性的值。