在Entity Framework的源代码(链接)中,我找到了这一行:
public virtual IRelationalTransaction Transaction
{ get; [param: NotNull] protected set; }
Run Code Online (Sandbox Code Playgroud)
这[param: NotNull]部分对我来说很奇怪.知道这是什么样的C#语法吗?我熟悉属性和参数,但不熟悉这种组合.
NotNull的定义是这样的:
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field)]
internal sealed class NotNullAttribute : Attribute
{
}
Run Code Online (Sandbox Code Playgroud)
我希望它被简单地用作[NotNull]但param在这里做什么?
Bac*_*cks 59
当用NotNull它标记方法时,该方法返回的不是null对象:
[NotNull]
public object Get()
{
return null; //error
}
Run Code Online (Sandbox Code Playgroud)
当你标记setter时它会做同样的事情 - setter返回not null(因为.net将属性转换为get和set方法).
public virtual IRelationalTransaction Transaction { get; [NotNull] protected set; }
Run Code Online (Sandbox Code Playgroud)
等于:
[NotNull]
public virtual void set_Transaction(IRelationalTransaction value) { ... }
Run Code Online (Sandbox Code Playgroud)
所以,你需要添加param:点,"我的意思是 - setter的参数不是null,不是set-method的结果":
public virtual IRelationalTransaction Transaction { get; [param: NotNull] protected set; }
Run Code Online (Sandbox Code Playgroud)
等于:
public virtual void set_Transaction([NotNull] IRelationalTransaction value) { ... }
Run Code Online (Sandbox Code Playgroud)
Oli*_*bes 40
param:是属性目标.请参阅:17.2属性规范
属性目标可以是以下之一:
程序集,模块,字段,事件,方法,参数,属性,返回,类型
因此[param: NotNull]意味着NotNullAttribute适用于valuesetter 的参数.由于value参数未显式显示为方法参数,因此必须在此处指定目标.
属性 - 目标的一个常见用途是指定InternalsVisibleToAttribute以使类型和成员声明为internal单元测试项目可见.
[assembly:InternalsVisibleTo("UnitTestProject")]
Run Code Online (Sandbox Code Playgroud)
程序集不显示为语言构造,因此属性目标assembly是指定程序集属性的唯一方法.顺便说一句:它可以在任何源代码文件中指定.
| 归档时间: |
|
| 查看次数: |
5283 次 |
| 最近记录: |