是否可以以某种方式创建 Foo<T> 对象的集合,其中 T 被限制为不可空类型?
Is it somehow possible to create a collection of Foo<T> objects where T is restricted to a non-nullable type?
在 class 我有以下结构
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
属性只是标记自动依赖项注入的目标。
在 class 中,我需要为每个 StateGroup
对象调用完全相同的代码块,并且我想将它们全部添加到一个集合中并对其进行迭代。但是我无法定义任何类型 StateGroup<IAgentState>[]
的集合,因为它需要一个不可为 null 的类型参数 并且我不能从 where 子句 中删除结构,因为 ComponentDataArray
StateGroup
的也需要一个结构!
除了编写一个我为每个 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);
在 class 我有以下结构
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
属性只是标记自动依赖项注入的目标。
在 class 中,我需要为每个 StateGroup
对象调用完全相同的代码块,并且我想将它们全部添加到一个集合中并对其进行迭代。但是我无法定义任何类型 StateGroup<IAgentState>[]
的集合,因为它需要一个不可为 null 的类型参数 并且我不能从 where 子句 中删除结构,因为 ComponentDataArray
StateGroup
的也需要一个结构!
除了编写一个我为每个 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);