【问题标题】:How can I test if an object has a property and set it?如何测试对象是否具有属性并设置它?
【发布时间】:2016-11-09 08:45:35
【问题描述】:

我在 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 不包含修改的属性。

【问题讨论】:

  • 相关(不完全重复):stackoverflow.com/questions/2998954/…
  • 您可以使用反射来制作一些东西,但是您的问题中有一点代码味道。为什么Modified 不是IAuditableTable 上的属性?
  • 使用refelction var myproperty = table.GetType().GetProperty("modified")
  • 你的意思是你现在不想修复你的设计,但以后甚至有 更多 代码取决于它?
  • 好吧,你总是可以有另一个接口,IModificationRecord 或其他东西,并检查table 是否实现了该接口...

标签: c#


【解决方案1】:

使用反射:

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

【讨论】:

  • 但是如何设置值,因为它报告 IAuditableTable 不包含修改的属性
猜你喜欢
  • 2015-09-20
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2022-07-01
  • 2014-12-24
  • 2015-09-27
  • 1970-01-01
  • 2017-03-16
相关资源
最近更新 更多