开发者

What are [] in C#?

For example:

    [TestFixtureSetUp]
    public void Init()
    {
        GetTestRepo(false)开发者_JAVA百科;
    }

[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.

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.

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).

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.

(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])


Attributes. You can find more information here.


It is an Attribute


It's an attribute. Sort of like MetaData for the class/function you use it on.


They are called attributes (analogous to Java annotations) and they are compiled in as meta data.


You appear to be recreating a basic VB/C# faq by asking one question at a time in SO. To add to that, it does appear to be a good way to get reputation.

To answer the TITLE, [] are the symbols used to

  • index into arrays
  • enclose an attribute (metadata) on a method
  • one other thing I can't remember

VB.Net uses the <> characters for the same purpose on metadata, but uses () to indicate array access.
Java uses a leading "@" for the same purpose

If you didn't have those special characters, the compiler couldn't interpret what you wrote. Not sure what else you want to know. Do you want to know the meaning of TestFixture?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜