什么是[参数:NOTNULL]在C#是什么意思? [英] What does [param: NotNull] mean in C#?

查看:708
本文介绍了什么是[参数:NOTNULL]在C#是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实体框架的源$ C ​​$ C(<一个href=\"https://github.com/aspnet/EntityFramework/blob/dev/src/EntityFramework.Relational/Storage/RelationalConnection.cs#L74\">link)我发现这行:

In Entity Framework's source code (link) I found this line:

public virtual IRelationalTransaction Transaction 
{ get; [param: NotNull] protected set; }

[参数:NOTNULL] 部分看起来很奇怪,我。任何想法什么样的一个C#语法的东西?我熟悉的属性和参数而不是这个组合。

The [param: NotNull] part looks very strange to me. Any idea what kind of a C# syntax is this? I'm familiar with attributes and param but not this combination.

NOTNULL的定义是这样的:

The definition of NotNull is this:

[AttributeUsage(
    AttributeTargets.Method | AttributeTargets.Parameter |
    AttributeTargets.Property | AttributeTargets.Delegate |
    AttributeTargets.Field)]
internal sealed class NotNullAttribute : Attribute
{
}

这我想像的要简单地用作 [NOTNULL] 但什么是参数在这里做什么?

Which I expected to be used simply as [NotNull] but what is param doing here?

推荐答案

当你标记与 NOTNULL 方法就意味着,该方法返回没有空对象:

When you mark method with NotNull it means, that method returns not null object:

[NotNull]
public object Get()
{
    return null; //error
}

当你标记二传手它同样 - 二传手返回NOT NULL(因为.NET转换属性get和set方法)

When you mark setter it does the same - setter returns not null (because .net converts properties to get and set methods).

public virtual IRelationalTransaction Transaction { get; [NotNull] protected set; }

等于:

[NotNull] 
public virtual void set_Transaction(IRelationalTransaction value) { ... }

所以,你需要添加参数:来一点,说:我的意思是 - 二传的参数不为null,集法不结果:

So, you need to add param: to point, that "i mean - parameter of setter is not null, not a result of set-method":

public virtual IRelationalTransaction Transaction { get; [param: NotNull] protected set; }

等于:

public virtual void set_Transaction([NotNull] IRelationalTransaction value) { ... }

这篇关于什么是[参数:NOTNULL]在C#是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆