C#通过反射给对象赋值

时间:2023-11-15 19:38:20
class Program
{
static void Main(string[] args)
{
UserSearchRequest model = new UserSearchRequest()
{
Name = "'1'=0",
Age =
}; Type type = model.GetType();
//var ps = type.GetProperties(); var ps = type.GetProperties().Where(u=>u.PropertyType.FullName =="System.String").ToList(); foreach (var p in ps)
{
Console.WriteLine("PropertyName:{0},Value:{1}",p.Name,p.GetValue(model,null).ToString());
p.SetValue(model, "",null);
Console.WriteLine("PropertyName:{0},Value:{1}", p.Name, p.GetValue(model, null).ToString());
} Console.ReadLine();
}
} public class UserSearchRequest
{
public string Name { set; get; }
public int Age { set; get; }
}