c# - 如何测试对象是否具有属性并设置它?

标签 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 不包含修改后的属性。

最佳答案

使用反射:

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

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

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

关于c# - 如何测试对象是否具有属性并设置它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38238574/

相关文章:

c# - 创建从 AppDomain 引用的对象的本地实例

c# - 如何检查 Zebra 105SL 打印机是否正常/就绪

c# - ViewResult.StatusCode 为空,尽管已明确设置

c# - 我正在尝试在 opentk 中实现索引缓冲区对象,但不知道在绘制东西时如何实际使用它

c# - 用于 web.config 和 app.config 的单个 NuGet 转换文件

C#接口(interface)问题

c# - Command 中 Item 与 UI 的绑定(bind)(初级)

c# - 我怎样才能使这些方法通用?

c# - jQuery 中有一些处理时间段数据类型的方法吗?

c# - 为什么不能在 Visual Studio 2013 的条件断点中使用 lambda?