I am trying to make a generic method that can accept any object, in which, even the object is List<AnyClass>
.
Something like:
public static void MyMethod(object _anyObject)
{
}
So in my method it accept the parameter as Object, then I will determine what to do by their type to do
So when I know that's a List type, I want to convert that Object back to List<AnyClass>
, iternate each object and their propertie
I tried to do:
List<object> ObjectList = object as List<object>;
But it will return null
, because the object originally is List<AnyClass>
Thanks in advance
================
Edit: Sorry, seems like I haven't make it clear, because I simplifed the problem... I means the Object might be:
_anyObject = List<Class1>
_anyObject = Class2
_anyObject = DataSet
_anyObject = AnyClass
_anyObject = List<object>
So say, the user can even put in a List<object>
, but each of the object in that list can be different class..That's why I can't use <T>
.
The original of my problem is:
public static void MyMethod(List<object> _anyList)
{
}
Then I don't care what they put into the list, even the object in the list contains another object list...
Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);
toList()) can be used to collect Stream elements into a list. We can leverage this to convert object to a list.
You could create a list of Object like List<Object> list = new ArrayList<Object>() . As all classes implementation extends implicit or explicit from java. lang. Object class, this list can hold any object, including instances of Employee , Integer , String etc.
It sounds like you should use method overloading instead of type detection. This will also break your single large method up into smaller, more maintanable methods.
public static void MyMethod(List<AnyClass> list)
{
foreach (var obj in list)
{
MyMethod(obj);
}
}
public static void MyMethod(AnyClass single)
{
//work with single instance
}
The generic List class implements the non-generic IList interface, so you can say:
IList objectList = obj as IList;
However, what you're trying to do is generally considered bad practice as it eliminates any semblance of type safety. If you explain in what context you're using this, we might be able to suggest a better alternative, like using a generic method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With