[英]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. 但是,如果传递类型为MyList<ExampleMyRecordClass, SomeIntEnum>
的列表,则此方法实际上不起作用,因为隐式上载不适用于泛型类型。 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. 因为我真正想要的只是属性id
,所以我当然可以在MyList<T, E>
中显式实现属性或方法,该属性或方法返回带有此信息的新集合。
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? 是否有办法(可能是隐式运算符,或者是要在MyList<T, E>
实现的其他接口)使之成为可能?
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 : IReadOnlyList <T>接口 :
public interface IReadOnlyList<out T> : IEnumerable<T>
{
int Count { get; }
T this[int index] { get; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.