课程: C# Practice: Attributes

Solution: Obsolete attribute - C#教程

课程: C# Practice: Attributes

Solution: Obsolete attribute

- [Instructor] The goal for this challenge was to apply an existing .NET attribute, the obsolete attribute, to the condition property and to the update value method. So here's how I solve the challenge. On line 22 is where I'm declaring the condition property. So on the line above that, I use the obsolete attribute here. In C# you use the square braces around the attribute. And in this case there is an optional parameter, the string parameter, which is the message, and I've added a value there. There's a alternate syntax that uses the longer name. The actual type name is obviously the attribute. So I'm using that here on line 25. Whereas on line 21, I use the shorthand version of that. The C# compiler will compile both of these to the correct type and it'll inject the correct metadata into the .NET assembly. So that's the solution. If I run the test my code, I can see that the update value method is marked as obsolete and the condition property is marked as obsolete. Now, I did want to talk about working with multiple attributes. If you haven't seen how to do that, I've got an example up here on the collective card class itself. So let's uncomment these. What I'm using here is two separate attributes, the obsolete attribute and the serializable attribute. And I'm using the stacked format, where each item is on a separate line in the code editor. It's also possible to use them side by side like this. And if you want, you can remove the additional square braces and put a comma between the two of 'em. So this is legal syntax too. So those are three legal syntaxes for applying multiple attributes. Now this is nice and readable in this simple format. If you start adding extra values like we're doing here with extra strings and other values that you're assigning to the attribute, this will get messy. So in that case, I would go back and use it like this. I would use the stacked format.

内容