对值元组使用属性

Use attributes for value tuples

在 C# 7.0 中,.NET 引入了新的 return 值元组类型(函数式编程),因此代替:

[NotNull]
WrapperUser Lookup(int id)

我想使用值元组:

(User, Info) Lookup(int id)

我想为这些 return 类型使用属性:

([NotNull] User, [CanBeNull] Info) Lookup(int id)

但是VS2017不允许我这样做。如何在不使用包装器的情况下使用属性 class?

你不能。

(User, Info) Lookup(int id)

只是

的语法糖
ValueTuple<User,Info> Lookup(int id)

ValueTuple 的类型参数不是属性的有效目标。除了包装器 class 之外,您唯一的选择是将类型参数包装在 NonNullable wrapper

(NonNullable<User>,NonNullable<Info>) Lookup(int id)

这让您可以像普通的 ValueTuple 一样使用它,例如

(NonNullable<User>,NonNullable<Info>) Lookup(int id) => (new User(), new Info());
(User user, Info info) = Lookup(5);

否则,您可以将自定义属性粘贴到整个 ValueTuple 中,指示哪些元组元素可以 null 与数组,例如用于为元组分配名称的 TupleElementNamesAttribute元组元素。不过,您必须编写自己的 visual studio / resharper 插件来完成这项工作。