繁体   English   中英

C#通用约束中的通配符

[英]Wildcards in C# generic constraints

我知道C#没有通用的通配符,并且泛型方法可以实现类似的效果,但是我需要在字段中使用通配符,如果有任何编码方法就无法解决。

List<State<Thing>> list;

void AddToList<T>() where T : Thing {
    list.Add(new State<T>());
}

当然,这不起作用,因为添加的对象不是State<Thing>类型,它是State<T> where T : Thing类型State<T> where T : Thing 是否可以将列表的最内部类型调整为Java等价物? extends Thing ? extends Thing而不仅仅是Thing

请注意,C#4确实具有额外的方差支持,但由于各种原因(具有“in”和“out”方法,并且是类),它不适用于List<T>情况。

但是,我认为解决这个问题的方法是:

interface IState { // non-generic
    object Value { get; } // or whatever `State<Thing>` needs
}
class State<T> : IState {
    public T Value { get { ...} } // or whatever
    object IState.Value { get { return Value; } }
}

List<IState> list; ...

然后, 它将允许您添加任何State<T> 它实际上没有使用太多的T ,并且需要从objectT ,但......它至少会起作用。

你可以尝试这样的事情:

    interface IState<out T> { }
    class State<T> : IState<T> { }
    class Thing {}

    List<IState<Thing>> list;

    void AddToList<T>() where T : Thing
    {
        list.Add(new State<T>());
    }

按以下方式声明您的列表:

class State<T> where T : Thing
{
    ...

    List<State<T>> list = new List<State<T>>();
    // or
    public class StateList<T> : List<State<T>>
    {
         void AddToList(T item);
    }
}

那么编译器就能转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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