编辑问题:这应该是清楚的。
using System;
namespace UpdateDateTimeFields
{
class Program
{
static void Main(string[] args)
{
string dateTimeFormat = "dd/MM/yyy HH:mm:ss";
DateTime time = DateTime.Now;
Update(time, dateTimeFormat); //Should update time
movemnet mymove = new movemnet();
mymove.FromDate = DateTime.Now;
mymove.ToDate = DateTime.Now;
mymove.Name = "Test_Movement";
Update(mymove, dateTimeFormat); //should update FromDate, ToDate
ParentClass cls = new ParentClass();
cls.mv.FromDate = DateTime.Now;
cls.mv.ToDate = DateTime.Now;
cls.CurrentDate = DateTime.Now;
cls.Comment = "ParentClass_Comment";
Update(cls, dateTimeFormat); //should update FromDate, ToDate, CurrentDate
}
private static void Update<T>(T Request, string format)
{
// How can this be acheived ???
//tried with Using Reflection to Get and Set values of Properties - NO JOY !!!
}
}
internal class movemnet
{
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public string Name { get; set; }
}
internal class ParentClass
{
public movemnet mv { get; set; }
public DateTime CurrentDate { get; set; }
public string Comment { get; set; }
}
}
答案 0 :(得分:0)
你不应该这样做。如果您希望您的班级以特定格式公开属性,您应该让您的班级这样做。您不应公开任何类的字段。您应该在头脑和代码中分离数据本身和数据视图。
绝对不应该使用反射来迭代类中的每个字段,检查DateTime的类型并设置格式。你绝对不应该做......
var fields = req1.GetType().GetFields(
BindingFlags.Instance | BindingFlags.NonPublic )
.Where( f=> f.FieldType == typeof( DateTime ) );
只要键入该代码我感觉很脏。 :)