[英]Changing property type in class that implements interface with object type property
[英]Class property defined as an object that implements interface
我有一组POCO类,它们实现了IConnectable
和IEntity
。
在其中一个类Connection
,我想要两个属性,这些属性被定义为实现IConnectable
对象。
public interface IConnectable
{
string Name { get; set; }
string Url { get; set; }
}
和我的连接课
public partial class Connection : IEntity
{
public int Id { get; set; }
public T<IConnectable> From { get; set; }
public T<IConnectable> To { get; set; }
public ConnectionType Type { get; set; }
public double Affinity { get; set; }
public DateTimeOffset CreatedOn { get; set; }
}
我知道我不能使用通用对象属性 - 所以有没有其他方法可以做到这一点?
最有可能的是根本没有仿制药:
public partial class Connection : IEntity
{
public int Id { get; set; }
public IConnectable From { get; set; }
public IConnectable To { get; set; }
public ConnectionType Type { get; set; }
public double Affinity { get; set; }
public DateTimeOffset CreatedOn { get; set; }
}
如果重要的是Connection
实例返回更多派生类型,那么你需要使整个类具有通用性:
public partial class Connection<T> : IEntity
where T : IConnectable
{
public int Id { get; set; }
public T From { get; set; }
public T To { get; set; }
public ConnectionType Type { get; set; }
public double Affinity { get; set; }
public DateTimeOffset CreatedOn { get; set; }
}
如果您需要为这两个属性提供两种不同的IConnectable
类型,则需要使用通用参数:
public partial class Connection<TFrom, TTo> : IEntity
where TFrom : IConnectable
where TTo : IConnectable
{
public int Id { get; set; }
public TFrom From { get; set; }
public TTo To { get; set; }
public ConnectionType Type { get; set; }
public double Affinity { get; set; }
public DateTimeOffset CreatedOn { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.