【发布时间】:2009-08-31 14:26:53
【问题描述】:
在方法参数中使用基类型有什么好处?
这是一个示例:
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();
}
}
...我们可以改变类型,除了 Foo 之外的任何东西都会在运行时失败。
那么问题来了:当 R# 建议 参数可以是 'X' 类型时我应该怎么做?
PS。 Whysharper - a plugin that dovetails Resharper and StackOverflow 的另一种解释。人们说它很好,但缺乏很好的解释——希望我们能一起让它变得更好;)。
【问题讨论】:
-
我假设 Clone() 在 ICloneable 合同中。我认为 CopyMe 可以写得更好,这样它就不会在运行时失败。