简体   繁体   中英

Parameter can be declared with base type

Resharper says Parameter can be declared with base type for this code, how do I fix that, and what's the benefit? I'm very new to C# so sorry if I missed some basic concept..

IEnumerator RemoveGameObject(float waitTime, GameObject go) {
    yield return new WaitForSeconds(waitTime);
    Destroy(go);
}

I read this thread , but didn't understand it.. maybe I need to read up on base types..

It is a suggestion based on best practices, design guidelines and programming principles.

When creating and deciding on parameter types for methods, you should use a parameter type that meets the minimum requirements the method needs to perform its job. You would use the Interface which meets those requirements, or the lowest class in the inheritance chain which meets those requirements.

In your example the method " Destroy(p) " seems to only use properties or methods which not only exist in the GameObject , but also in its base type (the class it inherits from). " Destroy(p) " does not need the "extra stuff" that GameObject brings with it. So by using the base of GameObject , which meets the minimum requirements of what " Destroy(p) " needs to perform its duties, you allow any class derived from that base to also gain the ability to be passed in as a parameter to " Destroy(p) ".

An example: Consider this code (probably not the best, but should do)

public class Animal
{
    public void Eat(Food food) { }
    public void Breath() { }
}

public class Dog : Animal
{
    public void Bark() { }
}

public class Human : Animal
{
    public void Speak() { }
}

now i create a method like so:

 public void PerformLifeDuties(Human joe, Food food)
{
    joe.Eat(food);
    joe.Breath();
}

i just limited my code. Now i cannot pass in an Animal , a Dog or any derived type of Animal , I can only pass in a Human . Even though the only requirements for that method are for it to be an Animal , so I can call eat and breath . The better way would have been to make the parameter Animal .

 public void PerformLifeDuties(Animal animal, Food food)
{
    animal.Eat(food);
    animal.Breath();
}

now i can use this method with Human , Dog and derived types. If my method needed to make the Animal speak, then i would've needed to specify at least Human .

From Microsoft's page:

✓ DO use the least derived parameter type that provides the functionality required by the member.

You can check out some of Microsoft's C# design guidelines here: Parameter Design

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM