0

と を実装する一連の POCO クラスがIConnectableありIEntityます。

クラスの 1 つで、Connectionを実装するオブジェクトとして定義されている 2 つのプロパティが必要です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; }
}

一般的なオブジェクトをプロパティとして使用できないことはわかっています。これを行う他の方法はありますか?

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; }
}

IConnectable2 つのプロパティに対して2 つの異なる型を使用できるようにする必要がある場合は、ジェネリック パラメーターが必要です。

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 に答える