Action 构造是通用的,但它可以支持其中的通用类型吗?
下面显示的代码片段是我想要实现的目标。
我知道还有其他方法可以做到这一点,但我很好奇是否可以在 Action 构造中实现。
void SomeMethod()
{
Action<int> Initialize = //<T> and where T is all that stuff
(index) =>
{
T obj = new T();
obj.Initialize(index);
obj.DoWork();
};
Initialize<TypeA>(1);
Initialize<TypeB>(2);
}
最佳答案
不,基本上 - 或者至少,不在 Action
的单个实例中- 就泛型而言,单个实例本质上是封闭的。显然你可以使用常规的通用方法 Initialize<T>
。如果您需要一个Action
,那么它可能需要将类型作为参数:
Action<Type, int> init = (type, index) => {
ISomeInterface obj = (ISomeInterface)Activator.CreateInstance(type);
obj.Initialize();
obj.DoWork();
};
init(typeof(TypeA), 1);
init(typeof(TypeB), 2);
否则:
void Initialize<T>(int index) where T : new(), ISomeInterface {
T obj = new T();
obj.Initialize();
obj.DoWork();
}
void SomeMethod() {
Initialize<TypeA>(1);
Initialize<TypeB>(2);
}
您可以创建Action<int>
代表单独 Initialize<TypeA>(int)
和Initialize<TypeB>(int)
,但不能同时两者,并且不能打开 Initialize<T>(int)
.
关于c# - Action 中的通用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26672740/