[英]Class property defined as an object that implements interface
I have a set of POCO classes which implement IConnectable
and IEntity
. 我有一组POCO类,它们实现了IConnectable
和IEntity
。
In one of the classes, Connection
, I want two properties that are defined as objects that implement IConnectable
. 在其中一个类Connection
,我想要两个属性,这些属性被定义为实现IConnectable
对象。
public interface IConnectable
{
string Name { get; set; }
string Url { get; set; }
}
And my connection class 和我的连接课
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; }
}
I know I can't use generic objects are properties -- so is there any other way to do this? 我知道我不能使用通用对象属性 - 所以有没有其他方法可以做到这一点?
It's most likely appropriate to just not have generics at all : 最有可能的是根本没有仿制药:
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; }
}
If it's important that instances of Connection
return types of something more derived then you'll need to make the whole class generic: 如果重要的是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; }
}
If you need to be able to have two different IConnectable
types for the two properties, then you need to generic parameters: 如果您需要为这两个属性提供两种不同的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.