问题
I was learning about NUnit and found we use class decorators like [TestMethod]
before every test function.
Then i learnt about decorators at this link. According to this answer
When You add decorator in C# it is like adding a property to the class/method. There will be an attribute attached to it.
I just want to ask if I want to use property to be used in whole class (not talking about one method) then why don't I choose inheritance over class decorator
What is the difference ...
回答1:
Be careful because the link you provided is using the word Decorator to refer to 2 entirely different concepts. The question in that link is asking this question:
What does it mean to Decorate a class or parameter?
What's the purpose and when would I do this?
Some answers, answer the question correctly specifically this and this. Both of these are talking about the Decorator Pattern.
However, this answer is talking about something entirely different. Although decorator can be used to mean Attributes (the ones with square brackets in C#) but that SO thread is using it to mean both the Decorator Pattern and Attributes.
Attributes
Attributes are explained here.
Decorator Pattern
Decorator Pattern pattern is explained here.
Decorator Pattern vs Inheritance
There is a good comparison here.
回答2:
The main difference is there could be exponentially many sub classes if you use inheritance over decorator.
The main point of using attribute decorator like that is for cross-cutting concern, you can reuse the same decorator across many classes & methods (reusable)
In your case, it's entirely different. [TestMethod]
is used as a "marker" instead of as a decorator to let the framework know which method is a test method. I don't see any relationship to inheritance in this case.
You could also use interfaces as "marker", but it's not as flexible as using attributes in this case.
来源:https://stackoverflow.com/questions/52788992/difference-between-class-decorator-and-inheriting-class