简体   繁体   中英

c# covariance with Interface and BindingList

Could not understand problem here:

public interface ILinkedTabularSectionManager<out T1> where T1 : TabularBusinessObject
{
    T1 LinkedTabularBusinessObject { get; }

    BindingList<T1> DataSource { get; }
}

C# Invalid variance: The type parameter must be invariantly valid on. is covariant.

Error is related to BindingList declaration.

Thanks.

A covariant interface can only return covariant generic types that use the type varable. That means the return value of the DataSource property must also be covariant. BindingList is not covariant, so it can not be returned by a method or property of a covariant interface. The closest covariant interface to a BindingList<T> is IReadOnlyList<T> ( BindingList<T> implements it), so you might want to use this one:

public interface ILinkedTabularSectionManager<out T1> where T1 : TabularBusinessObject
{
    T1 LinkedTabularBusinessObject { get; }

    IReadOnlyList<T1> DataSource { get; }
}

When declaring variant type, you're limited to the single variance kind.

Eg, if T1 is covariant (your case) none of interface members can use invariant or contravariant data types:

// This is valid: T in IEnumerable<T> is covariant
public interface ILinkedTabularSectionManager<out T1> where T1 : TabularBusinessObject
{
    T1 LinkedTabularBusinessObject { get; }

    IEnumerable<T1> DataSource { get; }
}

// This is invalid: T in BindingList<T> is invariant
public interface ILinkedTabularSectionManager<out T1> where T1 : TabularBusinessObject
{
    T1 LinkedTabularBusinessObject { get; }

    BindingList<T1> DataSource { get; }
}

// This is invalid: T in Action<T> is contravariant
public interface ILinkedTabularSectionManager<out T1> where T1 : TabularBusinessObject
{
    T1 LinkedTabularBusinessObject { get; }

    Action<T1> SomeAction { get; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM