我定义了以下接口(interface):
public interface IAudit {
DateTime DateCreated { get; set; }
}
public interface IAuditable {
IAudit Audit { get; set; }
}
IAuditable
接口(interface)说明我将对哪些类进行 Audit
。 IAudit
接口(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/