我在C#中有此代码
foreach (var entry in auditableTableEntries)
{
IAuditableTable table = (IAuditableTable)entry.Entity;
table.ModifiedBy = userId;
table.ModifiedDate = dateTime;
if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
{
if (table.CreatedBy == null || table.CreatedBy == null)
{
table.CreatedBy = userId;
table.CreatedDate = dateTime;
}
}
}
Run Code Online (Sandbox Code Playgroud)
一些表对象具有属性modified,为此,我想将属性设置为秒数。自1970年以来。类似:
table.modified = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds
Run Code Online (Sandbox Code Playgroud)
但是,如何判断该表是否具有该属性?如果属性不存在,我不想设置该属性,因为我认为这会导致异常。
到目前为止,这是我尝试过的:
if (table.GetType().GetProperty("modified") != null)
{
// The following line will not work as it will report that
// an IAuditableTable does not have the .modified property
table.modified = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds
}
Run Code Online (Sandbox Code Playgroud)
但这是问题,因为IAuditableTable不包含修改后的属性,所以table.modified是无效的语法。
使用反射:
PropertyInfo propInfo
= table.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault(x => x.Name.Equals("modified ", StringComparison.OrdinalIgnoreCase));
// get value
if(propInfo != null)
{
propInfo.SetValue(table, DateTime.Now);
}
Run Code Online (Sandbox Code Playgroud)
或者像其他人指出的那样,您最好让您的类实现另一个接口,例如IHasModified和:
if(table is IHasModified)
{
(table as IHasModified).modified = //whatever makes you happy. ;
}
Run Code Online (Sandbox Code Playgroud)