首页 > 解决方案 > C# 在通用方法中对类型约束进行别名以便重用

问题描述

看看下面的代码。

void Foo1<T>() where T : struct, IBar1, IBar2, IBar3 {}
void Foo2<T>() where T : struct, IBar1, IBar2, IBar3 {}
void Foo3<T>() where T : struct, IBar1, IBar2, IBar3 {}

如何为每个声明右侧的约束设置别名,以使这些声明变得更短且更具可读性?

从概念上讲,我所追求的应该与此类似(无效的 C# 代码):

MyConstraint<T> = T : struct, IBar1, IBar2, IBar3;
void Foo1<T>() where T : MyConstraint {}
void Foo2<T>() where T : MyConstraint {}
void Foo3<T>() where T : MyConstraint {}

T : struct是我的用例中最关键的部分。

如果 C# 中没有这样的语法,你建议有什么替代方法来减少这里的混乱?

标签: c#generics

解决方案


推荐阅读