简体   繁体   中英

Implicitly cast a generic type to a non-generic equivalent

Given the following classes:

public abstract class MyRecordClass
{
    public int id { get; private set; }
}

public class ExampleMyRecordClass : MyRecordClass {}

public enum SomeIntEnum : int {}

public class MyList<T, E> : IList<T>
where T : MyRecordClass
{

}

public class MyOtherClass
{
    public void MyMethod(MyList<T, E> list) {}
}

, I'd like call the method like this:

MyList<ExampleMyRecordClass, SomeIntEnum> myList;
MyOtherClass myOtherClass;

myOtherClass.MyMethod(myList);

However, this won't actually work if passing a list of type MyList<ExampleMyRecordClass, SomeIntEnum> , since implicit upcasts don't work in generic types. Since all I really want is the property id , I can, of course, explicitly implement a property or method in MyList<T, E> that returns a new collection with this information.

What I'd prefer to do is have this done implicitly. Is there a way (an implicit operator, perhaps, or an additional interface to implement in MyList<T, E> ) to make this possible?

I'm not sure what exactly you're looking for, but if you make the following change it compiles and runs just fine:

public class MyOtherClass
{
    public void MyMethod<T, E>(MyList<T, E> list) where T : MyRecordClass { }
}

Are you perhaps looking for covariance ?

public class MyList<T, E> : IList<T>, IReadOnlyList<T>
    where T : MyRecordClass
{
}

public class MyOtherClass
{
    public void MyMethod(IReadOnlyList<MyRecordClass> list) { }
}

Usage:

MyList<ExampleMyRecordClass, SomeIntEnum> myList;
MyOtherClass myOtherClass;

myOtherClass.MyMethod(myList);

IReadOnlyList<T> Interface :

public interface IReadOnlyList<out T> : IEnumerable<T>
{
    int Count { get; }
    T this[int index] { 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