我定义了以下接口:
public interface IAudit {
DateTime DateCreated { get; set; }
}
public interface IAuditable {
IAudit Audit { get; set; }
}
IAuditable
接口定义了哪些类我将具有Audit
。 IAudit
接口是该类的实际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
),我想通过将IAuditable
对象传递给构造函数来创建IAudit
实例(来自上面的UserAdit
)。理想情况下,我希望有这样的代码:
if (myObject is IAuditable) {
var audit = new IAudit(myObject) { DateCreated = DateTime.UtcNow }; // This would create a UserAudit using the above example
}
然而我有一堆问题:
- 你无法创建接口的实例
- 代码中没有明确定义哪个
IAudit
适用于哪个IAuditable
- 我无法指定
IAudit
接口必须具有以IAuditable
为参数的构造函数
我确定这是许多人曾经遇到的设计模式,但我无法理解它。如果有人能向我展示如何实现这一点,我会非常感激。