开发者

How can I shorten this code snippet?

开发者 https://www.devze.com 2023-02-02 17:37 出处:网络
I\'m sorry for the vague title, I think you really have to see the snippet to know what I mean: float[] foo = new float[3];

I'm sorry for the vague title, I think you really have to see the snippet to know what I mean:

float[] foo = new float[3];
FillFoos(foo);
return foo;

I'd like to have that in one line (I use this snippet very often). How would that be poss开发者_开发百科ible?


If you can't alter the FillFoos function, then your snippet is as short as it can be.

You could, of course, do this:

float[] foo = new float[3]; FillFoos(foo); return foo;

But that's still three statements and is fairly tough to read.


You could just create a function:

public float[] GetFoos()
{
    float[] foo = new float[3];
    FillFoos(foo);
    return foo;
}

EDIT: If you need to change the size of the array and the method to populate the array then you could do this:

public float[] GetFoos(int count, Action<float[]> populateAction)
{
    float[] items = (float[])Array.CreateInstance(typeof(float), count);
    populateAction(items);
    return items;
}

then you can call it like this:

float[] items = GetFoos(3, FillFoos);

You can even make it generic:

public T[] GetFoos<T>(int count, Action<T[]> populateAction)
{
    T[] items = (T[])Array.CreateInstance(typeof(T), count);
    populateAction(items);
    return items;
}


In C#, you could make a generic function that allocates an array and uses a supplied delegate to fill it:

 public static T[] AllocAndFill<T>(Action<T[]> fillAction, int count)
 {
      T[] array = new T[count];
      fillAction(array);
      return array;
 }

And use it like this do:

 var result =  AllocAndFill<float>(FillFoos,3);


Wrap it in another method.

T[] GetObjects<T>(int length) 
{
    T[] foo = new T[length]; 
    FillFoos(foo); 
    return foo; 
}

Now, instead of using that snippet everywhere, just call GetObjects<Foo>(3).


If you can't change FillFoos, then you could write some kind of helper method (perhaps as an extension method on whatever object contains FillFoos).

public static class Extensions
{
    public static float[] SuperFoo(this FooObject foo, float[] floats)
    {
        foo.FillFoos(floats);
        return floats;
    }
}

Then:

return fooObj.SuperFoo(new float[3]);
0

精彩评论

暂无评论...
验证码 换一张
取 消