课程: C# Practice: Attributes

Solution: Reflection - C#教程

课程: C# Practice: Attributes

Solution: Reflection

- [Instructor] This is my solution to the challenge. Now, the way reflection works is there are multiple avenues that we could approach this. We can also work with link and some of the link operators. So your solution may be different than mine. This is how I solved it. So the first thing I did in the check for unit test method is I created a list of integers or I new up a new list of integers and I'll return that from this method. Next step is to get the methods on the collectible card class. So I use type of to get the type of this card, and then I call get methods. And then I'm only interested in some of the methods that might be declared in the type. So I'm using these binding flags. I only want instance methods that are public, and I'm only interested in the methods that are declared in my type. I'm not interested in any of the methods that are declared in any of its base classes. It gives me all the methods. Then I have a for each loop that goes over those methods. When I get an instance of the method here in the for each loop, I call get custom attributes, and I'm using this link operator here which is called of type. So I'm saying I'm only interested in custom attributes that are of type test method attribute, and then I'm using any to see if there's any results. So if this method has the test method attribute, then I'm going to read it. So that's what I'm doing here. I'm getting the of type. I have the instance now of that custom attribute, and then I can call dot first just in case there's more than one in the list. I get the first one, and then I get the timeout value. Once I have the timeout value, I add it to my result list. And as you can see there was two methods that had the timeout applied, and I read the values 55 for the first one and 37 for the second one.

内容