c使用return属性做什么
本文关键字:什么 属性 return 使用 | 更新日期: 2023-09-27 18:00:36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyTest
{
class Program
{
static void Main(string[] args)
{
Test1 t1 = call();
Console.Out.WriteLine(t1);
Console.ReadLine();
}
[return: Test2(g = 5)]
public static Test1 call()
{
Test1 t1 = new Test1();
Test2 t2 = new Test2();
return t1;
}
}
class Test1 : Attribute
{
}
class Test2 : Attribute
{
public int g;
}
}
这里的方法call()
只是返回Test1
对象,但是用类Test2(g = 5)
设置返回attrbite
的目的是什么?
应该有什么改变或发生吗?但什么都没发生。。。有人能解释一下发生了什么事吗?
它对Test2对象有什么影响?那个物体应该在哪里?
和其他属性一样,它只是一个属性-属性的用法取决于决定使用它的任何人。return
的属性相对罕见,但它完全合法,它只是可以通过反射检查的元数据。
据我所知,C#编译器对用于return
的属性没有任何特定的了解,但例如,您可以将其用于自己的代码契约。作为一个具体的例子,一些框架包括一个NotNullAttribute
,它在某种程度上被错误地应用于整个方法:
[NotNull] string Foo()
表示它不会返回null引用。我认为这将更合适(尽管不那么简洁(写为:
[return:NotNull] string Foo()
强调它是非null的返回值,而不是作为整个方法的属性。
返回的属性影响(或不影响:请参见下文(返回值,而不是函数本身。
但是,属性本身没有任何影响。它们被其他代码(包括编译器(用来修改系统的操作(例如,通过提供元数据(。在读取该属性之前,它只是程序集中未使用的数据。