ReSharper [CanBeNull] 和 [NotNull] 属性可以应用于 Action 或 Func 参数吗?
Can ReSharper [CanBeNull] and [NotNull] attributes be applied to an Action or Func argument?
ReSharper 有一套代码注释,可用于显式表达可供 IDE 使用的代码意图。两个最有用的注释是 [CanBeNull]
和 [NotNull]
属性,它们可以用在构造函数、属性和方法上,如下所示:
[CanBeNull]
private Foo DoSomething([NotNull] string text)
{
// ...
}
希望不大,但是有什么方法可以将这些属性分配给 Action 或 Func 参数吗?
我知道下面的代码是非法的(因为type arguments are not a valid target for attributes),但是有其他表达方式吗?
private void DoSomething(Action<[NotNull]string> processText)
{
///...
}
如果您愿意创建自定义委托类型,则可以这样做:
delegate void TextProcessor([NotNull] string text);
delegate void NullableTextProcessor([CanBeNull] string text);
private void DoSomething([NotNull] TextProcessor processText)
{
// ...
}
private void DoSomethingNull([NotNull] NullableTextProcessor processText)
{
// ...
}
不幸的是,CanBeNull 似乎没有在 lambda 语法中给出警告:
但您可能只想等待 C# 8 的 nullable/non-nullable 引用类型。
ReSharper 有一套代码注释,可用于显式表达可供 IDE 使用的代码意图。两个最有用的注释是 [CanBeNull]
和 [NotNull]
属性,它们可以用在构造函数、属性和方法上,如下所示:
[CanBeNull]
private Foo DoSomething([NotNull] string text)
{
// ...
}
希望不大,但是有什么方法可以将这些属性分配给 Action 或 Func 参数吗?
我知道下面的代码是非法的(因为type arguments are not a valid target for attributes),但是有其他表达方式吗?
private void DoSomething(Action<[NotNull]string> processText)
{
///...
}
如果您愿意创建自定义委托类型,则可以这样做:
delegate void TextProcessor([NotNull] string text);
delegate void NullableTextProcessor([CanBeNull] string text);
private void DoSomething([NotNull] TextProcessor processText)
{
// ...
}
private void DoSomethingNull([NotNull] NullableTextProcessor processText)
{
// ...
}
不幸的是,CanBeNull 似乎没有在 lambda 语法中给出警告:
但您可能只想等待 C# 8 的 nullable/non-nullable 引用类型。