c# - 创建接口(interface)实例

标签 c# interface

我定义了以下接口(interface):

public interface IAudit {
    DateTime DateCreated { get; set; }
}

public interface IAuditable {
    IAudit Audit { get; set; }
}

IAuditable 接口(interface)说明我将对哪些类进行 AuditIAudit 接口(interface)是该类的实际 Audit。例如说我有以下实现:

public class User : IAuditable {
    public string UserName { get; set; }
    public UserAudit Audit { get; set; }
}

public class UserAudit : IAudit {
    public string UserName { get; set; }
    public DateTime DateCreated { get; set; }

    public UserAdit(User user) {
        UserName = user.UserName;
    }
}

现在给定一个 IAuditable 的对象(上面的 User),我希望能够创建 IAudit 的实例(上面的 UserAdit)通过将 IAuditable 对象馈送到构造函数中。理想情况下,我会有类似的东西:

if (myObject is IAuditable) {
    var audit = new IAudit(myObject) { DateCreated = DateTime.UtcNow }; // This would create a UserAudit using the above example
}

但是我有一堆问题:

  • 您不能创建接口(interface)的实例
  • 没有在代码中的任何地方定义哪个 IAudit 适用于哪个 IAuditable
  • 我无法指定 IAudit 接口(interface)必须有一个采用 IAuditable 的构造函数

我敢肯定这是许多人以前使用过的设计模式,但我无法理解它。如果有人能告诉我如何实现这一点,我将不胜感激。

最佳答案

No where in the code does it define which IAudit applies to which IAuditable I can't specify that the IAudit interface must have a constructor which takes an IAuditable

您可以通过将 CreateAudit() 函数添加到您的 IAuditable 来解决这两个问题。然后您将获得一个从 IAuditable 创建的 IAudit。作为奖励,如果你想在 IAuditable 中存储对 IAudit 的引用(反之亦然),这样你就可以让它们相互关联,这很容易让一个实现类来做。例如,您还可以将 GetAuditable() 添加到 IAudit 以获取创建它的 IAuditable

简单的实现看起来像这样(在实现 IAuditable 的类上):

public IAudit CreateAudit()
{
    UserAudit u = new UserAudit(UserName);
    return u;
}

关于c# - 创建接口(interface)实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7122260/

相关文章:

java - 如何从彼此不关注的数字池中生成一个随机数

c# - 如何为 ASP.NET MVC 站点构建 CAPTCHA 验证架构?

c# - 如何从ASP.NET MVC 2中的Application_Error重定向?

c# - 以编程方式将新列添加到 DataGridView

c# - 如何在 C# 接口(interface)中使用泛型类型参数

c# - 使用 C# 检查工作站锁定/解锁更改

java - 具有 UnsupportedOperationException 实现的默认方法

java - 如何将参数传递给接口(interface)的一个实现者而不是其他实现者(不在构造函数中传递它)?

c# - 在 C# 中使用基本接口(interface)有什么好处

refactoring - 如果只有一个类实现它,那么接口(interface)是否有任何意义?