扩展方法问题。为什么我需要使用 someObj = someObj.somemethod();
我有一个简单的扩展方法,我想用它来将项目添加到项目数组中。
public static T[] addElement<T>(this T[] array, T elementToAdd)
{
var list = new List<T>(array) { elementToAdd };
return list.ToArray();
}
这工作正常,但是当我使用它时,我必须将数组设置为等于返回值。我看到我正在返回一个数组。我可能希望此方法无效,但我希望添加该项目。有谁对我需要做什么有什么想法,才能使这项工作按照我想要的方式进行?
我只想执行 someArray.addElement(item)
,而不是 someArray = someArray.addElement(item)
,然后 someArray 就可以开始了。我在这里缺少什么?
I have a simple extension method that I would like to use to add an item to an array of items.
public static T[] addElement<T>(this T[] array, T elementToAdd)
{
var list = new List<T>(array) { elementToAdd };
return list.ToArray();
}
this works ok, but when I use it, I am having to set the array equal to the return value. I see that I am returning an Array. I likely want this method to be void, but I would like the item added. Does anyone have any ideas on what I need to do , to make this work the way I am wanting?
Instead of someArray = someArray.addElement(item)
, I just want to do someArray.addElement(item)
and then someArray be ready to go. What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
内置数组具有固定大小,因此无法以这种方式进行修改。如果您想要动态大小的数组,请使用
List
。Built-in arrays have a fixed size and so can't be modified in this way. If you want a dynamically-sized array, use a
List<T>
.如果您可以使用 ref 扩展方法,那么这是可能的,但根本不是一个好方法。值得庆幸的是,他们不受支持。
如果您绝对必须有这样的东西,您可以使用带有
ref
参数的静态方法:但这与您当前的解决方案一样丑陋(如果不是更丑的话)。
If you could use
ref
extension methods then it would be possible, but not a good way to do things at all. Thankfully they are not supported.If you absolutely must have something like this you can use a static method with a
ref
parameter:But this is just as ugly (if not more so) than your current solution.
这是不可能的。调整数组大小的唯一方法是创建一个新数组。如果您需要经常向数组添加项目,请使用
List
,它们就是为此目的而设计的。It's not possible. The only way to resize an array is by creating a new one. If you need to frequently add items to an array, use a
List
, they are designed for this purpose.