0

I have a set of POCO classes which implement IConnectable and IEntity.

In one of the classes, Connection, I want two properties that are defined as objects that implement 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?

4

1 回答 1

2

根本没有泛型是最合适的:

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; }
}
于 2013-10-01T20:06:49.623 回答