什么是[]在C#中?

2023-09-04 22:40:20 作者:彼岸花撒落了一地

例如:

    [TestFixtureSetUp]
    public void Init()
    {
        GetTestRepo(false);
    }

[TestFixtureSetUp]在这个例子中,它有什么作用?从我的经验,[]通常是指列表。

[TestFixtureSetUp] in this example, what does it do? From my experience, [] usually refers to lists.

推荐答案

的属性。他们是一个办法添加元数据有关方法/属性/接口/类/命名空间在运行时检查。

Attributes. They are a way to add metadata about methods/properties/interfaces/classes/namespaces for inspection at runtime.

您的示例将 TestFixtureSetUpAttribute 的一种方法。这使得测试运行,以确定哪种方法在您的类设置文本夹具时运行。

Your example adds the TestFixtureSetUpAttribute to a method. This allows the test runner to determine which method in your class to run when setting up a text fixture.

测试运行加载测试组装成内存在运行时。然后,它通过你的程序集中定义的类都被打上了特定属性(无论NUnit的使用标志着一个测试类)枚举。亚军现在知道哪些类实例化运行测试。然后它看起来通过在该类中定义为将被运行,以建立测试夹具的方法的方法。它搜索每一个方法,你问的属性。一旦检测方法它知道在运行测试/每个测试(无论这意味着在NUnit的),然后运行该方法。

The test runner loads your test assembly into memory at runtime. It then enumerates through the classes defined within your assembly that have been marked with a particular attribute (whatever NUnit uses to mark a test class). The runner now knows what classes to instantiate to run tests. It then looks through the methods defined in the class for a method that will be run to set up the test fixture. It searches each method for the attribute you asked about. Once it finds that method it knows to run that method before running tests/each test (whichever it means in NUnit).

属性是所有关于增加有关,你可以在运行时搜索方法的信息。它的那种东西在那里,如果你不需要他们你千万不要错过他们,但是当你需要'时间OMFG是伟大的​​,他们可用。

Attributes are all about adding information about a method that you can search for at runtime. Its the kind of thing where if you don't need 'em you don't miss 'em, but when you DO need 'em OMFG is it great that they're available.

(在C#中,你可以省略类型名的属性,编译器知道你在说什么,比如,SerializableAttribute当你说 [Serializable接口]

(In C#, you can omit the "Attribute" from the type name. The compiler knows you're talking about, for instance, "SerializableAttribute" when you say [Serializable])

相关推荐