Resharper suggests parameter can be of type 'BaseType'

让人想犯罪 __ 提交于 2019-12-17 18:39:13

问题


what are the benefits of using base types in method parameters?

Here's one sample:


private void Foo(List<int> numbers) //R# laments: parameter can be IEnumerable. 
{
    foreach (var i in numbers) {
        Console.WriteLine(i);
    }
}



And here's another one


public class Foo : ICloneable
{
    public object Clone()
    {
        return MemberwiseClone();
    }

    public Foo CopyMe(Foo other) //R# laments: parameter can be ICloneable
    { 
        return (Foo)other.Clone();
    }
}

...where we can change the type and anything but Foo will fail at runtime.



So the question: what should I do when R# suggests parameter can be of type 'X'?




PS. Just another explanation for Whysharper - a plugin that dovetails Resharper and StackOverflow. People say it's nice but lacks good explanations - hopefully together we can make it better ;).


回答1:


Using base types for parameters has the following benefits:

  • Reduces unnecessary coupling in your code
  • Makes your code more flexible by allowing a broader range of valid inputs
  • Makes your code safer by limiting the types of operations that can be performed on the input
  • Improves performance of your code by reducing the need to perform conversions between types

However, you shouldn't always us a base type in a method call just because a tool like ReSharper says it is possible. You should make sure that the usage and semantics of the methods are clear - and that future changes are not likely to require moving down the inheritance hierarchy - potentially breaking existing code.

In your examples above, using IEnumerable instead of List makes it possible for callers of your code to pass in not just List objects but also arrays, Stacks, Queues, and even results from LINQ calls (which primarily return IEnumerable). Since your code only iterates over the collection, it doesn't need to know about List. It also means that consumers of your code won't have to convert their collections into copies of type List just to pass them to your method.




回答2:


It's the Liskov Substitution principle



来源:https://stackoverflow.com/questions/1357727/resharper-suggests-parameter-can-be-of-type-basetype

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!