这是我的代码,我收到错误:“只能在Type.IsGenericParameter为true的Type上调用方法。”
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CustomInfo obj = new CustomInfo();
var stringProperties = obj.GetType().GetProperties()
.Where(p => p.PropertyType == typeof(string));
foreach (var stringProperty in stringProperties)
{
string currentValue = (string)stringProperty.GetValue(obj, null);
stringProperty.SetValue(obj, currentValue.Trim(), null);
}
}
}
public class CustomInfo
{
int UserId { get; set; }
string UserName { get; set; }
string Country { get; set; }
string City { get; set; }
DateTime DOB { get; set; }
bool isActiveUser { get; set; }
}
我无法修剪对象中的所有字符串属性。
答案 0 :(得分:0)
您显示的代码执行foreach
循环零次,因为您的属性是非公开的。
如果您解决了这个问题,则会得到null
引用异常,因为您从属性getter中读取了null
字符串,然后在Trim()
上调用了null
。
使用您提供的代码似乎没有比这些更多的问题。如果您需要其他一些代码的帮助,请更新您的问题。