C#通过反射设置对象DateTime属性值

Mik*_*ike 7 .net c# reflection system.reflection c#-4.0

我想将我的对象的所有DateTime属性设置为默认日期.但是,如果我尝试通过反射设置值,我会得到异常:"对象与目标类型不匹配".

private void SetDefaultValues()
{
    DateTime dt = DateTime.Parse("1/1/2000", new CultureInfo("en-US", true));
    foreach (PropertyInfo p in this.GetType().GetProperties())
    {
        if (p.PropertyType.FullName == "System.DateTime")
        {                                      
            p.SetValue(dt, typeof(DateTime), null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在做/思考一些根本不正确的事情吗?

Mar*_*ell 9

参数需要调整; 第一个是目标 - 我假设在this这里; 所述第二是值(dt).最后一个涉及"索引器" - 这可能不适用于此.

p.SetValue(this, dt, null);
Run Code Online (Sandbox Code Playgroud)