ReSharper的暗示参数可以是类型为“基本类型” [英] Resharper suggests parameter can be of type 'BaseType'

查看:674
本文介绍了ReSharper的暗示参数可以是类型为“基本类型”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是方法参数使用基本类型的好处

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

这里有一个例子:


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






和这里的另一个


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.




所以问题:我应该当R#表明我的参数可以是类型的'X'






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




PS。只是另一种解释 Whysharper - 即吻合ReSharper的和计算器插件。人们说这是不错,但缺乏很好的解释 - 希望我们可以一起做的更好。)

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 ;).

推荐答案

使用基本类型的参数有以下好处:

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

不过,你不应该总是我们一个方法调用基类仅仅因为一个像ReSharper的工具,说,这是可能的。你应该确保在使用和方法语义明确 - 那未来的变化不太可能需要向下移动的继承层次 - 可能破坏现有的代码

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.

在上面你的例子,使用的IEnumerable而不是List它使你的代码的调用者的不仅仅是List对象也是数组,栈,队列,甚至从结果称LINQ(这主要是返回IEnumerable的)通过。由于您的代码仅在集合迭代,它并不需要了解列表。这也意味着你的代码的消费者不会有自己的藏品转换为List类型的副本只是将它们传递给你的方法。

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.

这篇关于ReSharper的暗示参数可以是类型为“基本类型”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆