Reputation: 2963
I have the following problem:
I am currently writing the c# equivalent of PHP's var_dump
-method. It works perfectly with 'simple' classes and structures (and even with arrays).
My only problem is when it comes to other IEnumerable<T>
, like List<T>
etc:
The debugger is throwing an TargetParameterCountException
. My code looks as follows:
Type t = obj.GetType(); // 'obj' is my variable, i want to 'dump'
string s = "";
PropertyInfo[] properties = t.GetProperties();
for (int i = 0; i < properties.Length; i++)
{
PropertyInfo property = properties[i];
object value = property.GetValue(obj); // <-- throws exception
if (value is ICollection)
{
// Code for array parsing - is irrelevant for this problem
}
else
s += "Element at " + i + ": " + value.GetType().FullName + " " + value.ToString() + "\n";
}
return s;
I know, that i can somehow fetch indices with PropertyInfo.GetIndexParameters()
, but I did not figured out, how to use it correctly.
Edit: I also want to note that I neither know the size of the IEnumerable, nor the Type T at compile time.
Upvotes: 3
Views: 3135
Reputation: 277
If you want the reference to the IEnumerable and not only it's items you can get it using :
if (propertyInfo.GetMethod.IsPublic)
{
var value = propertyInfo.GetMethod.Invoke(Instance, null);
}
Upvotes: 1
Reputation: 62015
Use the GetIndexParameters()
method of PropertyInfo
to determine whether the property is indexed, and if it is, either skip it, or go back to the drawing board and see how you can generate the index(es) that it needs in order to return a meaningful value without failing.
Upvotes: 1
Reputation: 3580
Not exactly sure if this is your problem, but according to MSDN:
You call the GetValue(Object) overload to retrieve the value of a non-indexed property; if you try to retrieve the value of an indexed property, the method throws a TargetParameterCountException exception.
From the example on the same page:
if (prop.GetIndexParameters().Length == 0) Console.WriteLine(" {0} ({1}): {2}", prop.Name, prop.PropertyType.Name, prop.GetValue(obj)); else Console.WriteLine(" {0} ({1}): <Indexed>", prop.Name, prop.PropertyType.Name);
Upvotes: 3
Reputation: 203827
This has nothing to do with the type implementing IEnumerable
. Rather it's about the type having an indexer. Indexers are considered properties, but they're special properties that need to be given the parameter of the index when getting their value. If you don't, it errors as you're seeing here.
You can use GetIndexParameters()
and check the count of the returned array to determine if the property is an indexer. This will let you either skip that property (which is what I assume you'll want to do here), or use it to get its values.
Upvotes: 1