如何测试对象是否具有属性并进行设置?

时间:2016-07-07 06:11:58

标签: c#

我在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;
                }
            }

        }

某些表对象具有属性modified,对于这些,我想将属性设置为秒数的值。自1970年以来。像:

        table.modified = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds

但是如何判断该表是否具有该属性?我不想设置属性,如果它不存在,因为我认为会导致异常。

这是我到目前为止所尝试的内容:

      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
      }

但问题是table.modified不是有效语法,因为IAuditableTable不包含修改后的属性。

1 个答案:

答案 0 :(得分:4)

使用反射:

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);
}

或者正如其他人所指出的那样,你最好让你的类实现另一个接口,例如IHasModified和:

if(table is IHasModified)
{
    (table as IHasModified).modified = //whatever makes you happy. ;
}
相关问题