C#: returns array from object
There is the next task: I need to check if input parameter (object) is array, then return array of input elements. For example I have input array like this:
int [开发者_高级运维] array = {1,2,3,4};
And method
private object[] GetArray(object @from)
{
}
So, I need to check in this method that input variable is array and after return this array. For checking I use
if(@from.GetType().IsArray)
And how to create array from object ??? Is it possible ? Thanks.
If what you want to do is return @from
as an object[]
-- if it is already an object[]
-- then the simplest way is just:
private object[] GetArray(object @from)
{
return @from as object[] ?? new object[] { @from };
}
The above might look kind of confusing. Here's how it works:
- If
@from
is anobject[]
to begin with, it just returns that (typed as such). - Other wise, the expression
@from as object[]
evaluates tonull
. In this case, the null-coalescing operator (??
) evaluates the following expression:new object[] { @from }
.
So the result is that this method returns either the already existing object[]
array, or an array of length 1 containing @from
.
On the other hand, if you want to populate an object[]
from the contents of @from
, I'd do this:
private object[] GetArray(object @from)
{
var objects = @from as IEnumerable;
if (objects != null)
return objects.Cast<object>().ToArray();
return new object[] { @from };
}
As LukeH pointed out, you could also check to make sure @from
is not a string
, if you don't want GetArray(string)
to return an object[]
containing char
elements:
private object[] GetArray(object @from)
{
var str = @from as string;
if (str != null)
return new object[] { str };
var objects = @from as IEnumerable;
if (objects != null)
return objects.Cast<object>().ToArray();
return new object[] { @from };
}
you can use arraylist for this task... We can add any object to a arraylist and you can return it then
Without knowing what the object is, creating an array is a very ambiguous task. What values do you want in the array? Do these values have some deeper meaning. These really are things the object should know about itself and you don't necessarily care to know the details.. For example a Collection
has a CopyTo
method that performs this task.
精彩评论