是否可以以某种方式创建T限制为非空类型的Foo <t>对象的集合?

时间:2018-09-08 18:54:23

标签: c# collections nullable non-nullable

在类中,我具有以下结构

private struct StateGroup<TState> where TState : struct, IAgentState
{
    // ...
    // ComponentDataArray requires TState to be a struct as well!
    public ComponentDataArray<TState> AgentStates;
    // ...
}

和该类型的多个对象

[Inject] private StateGroup<Foo> _fooGroup;
[Inject] private StateGroup<Bar> _barGroup;
[Inject] private StateGroup<Baz> _bazGroup;
// ...

具有Inject属性的对象仅标记了自动依赖项注入的目标。

在类中,我需要为每个StateGroup对象调用相同的代码块,并且我想将所有代码都添加到集合中并对其进行迭代。但是,我无法定义任何类型为StateGroup<IAgentState>[]的集合,因为它需要一个不可为null的类型参数,并且我也不得从where子句中删除该结构,因为{{ 1}}也需要一个结构!

除了编写一个方法为每个ComponentDataArray对象手动调用十二遍之外,是否有任何合理的方法将这些对象添加到集合中并为每个元素调用该特定方法?

1 个答案:

答案 0 :(得分:0)

您可以为StateGroup<TState>创建另一个不受struct约束的接口:

private interface IStateGroup<TState> where TState : IAgentState { }

然后我们使StateGroup实施新接口:

private struct StateGroup<TState>: IStateGroup<IAgentState> where TState: struct, IAgentState { }

并进行测试:

var states = new List<IStateGroup<IAgentState>>();
var fooGroup = new StateGroup<Foo>();
var booGroup = new StateGroup<Boo>();
var mooGroup = new StateGroup<Moo>();
states.Add(fooGroup);
states.Add(booGroup);
states.Add(mooGroup);