是否有可能以某种方式创建一个 Foo 对象的集合,<T>其中 T 仅限于不可为空的类型?



在一个类里面,我有以下结构

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>[]的集合,因为它需要一个不可为空的类型参数,并且我不能从 where 子句中删除结构,因为StateGroupComponentDataArray也需要结构!

除了为每个StateGroup对象手动调用十几次之外,是否有任何合理的方法将它们添加到集合中并为每个元素调用该特定方法?

您可以在没有struct约束的情况下为StateGroup<TState>创建另一个接口:

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);