填充 Web 服务的请求对象,我需要将项目动态添加到一些数组。
我希望通过实现扩展方法来简化它:
public static class ArrayExtensions<T> where T : class
{
public static T[] Extend<T>(T[] originalArray, T addItem)
{
if (addItem == null)
{
throw new ArgumentNullException("addItem");
}
var arr = new[] { addItem };
if (originalArray == null)
{
return arr;
}
return originalArray.Concat(arr).ToArray();
}
}
所以这个旧代码:
if (foo.bazArr == null)
{
foo.bazArr = new[] { baz };
}
else
{
foo.bazArr = new[] { baz }.Concat(foo.bazArr).ToArray(); // (i know this inserts the new item at the beginning, but that's irrelevant, order doesn't matter)
}
可以改写为:
foo.bazArr = foo.bazArr.Extend(baz); // won't compile
错误是:'System.Array' does not contain a definition for 'Extend' and no extension method 'Extend' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)
而像这样直接调用扩展方法:
foo.bazArr = ArrayExtensions<someService.bazType>.Extend(foo.bazArr, baz);
编译得很好。
为什么呢?如果数组是强类型的,为什么编译器不能在这里自行推断类型?
编辑- 下面的正确代码:
public static class ArrayExtensions
{
public static T[] Extend<T>(this T[] originalArray, T addItem) where T : class
{
if (addItem == null)
{
throw new ArgumentNullException("addItem");
}
var arr = new[] { addItem };
if (originalArray == null)
{
return arr;
}
return originalArray.Concat(arr).ToArray(); // although Concat is not recommended for performance reasons, see the accepted answer
}
}
对于这个流行的问题,这是另一个很好的简单示例:
public static class Extns
{
// here's an unbelievably useful array handling extension for games!
public static T AnyOne<T>(this T[] ra) where T:class
{
int k = ra.Length;
int r = Random.Range(0,k);
return ra[r];
// (add your own check, alerts, etc, to this example code)
}
}
并在使用中..
someArrayOfSoundEffects.AnyOne().Play();
someArrayOfAnimations.AnyOne().BlendLeft();
winningDisplay.text = successStringsArray.AnyOne() +", " +playerName;
SpawnEnormousRobotAt( possibleSafeLocations.AnyOne() );
等等。对于任何数组,它都会给你一个随机项目。在游戏中经常用于随机化效果等。数组可以是任何类型。