Wie kann man „ICollection“ in „IEnumerable“ umwandeln, ohne T zu kennen?C#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Wie kann man „ICollection“ in „IEnumerable“ umwandeln, ohne T zu kennen?

Post by Anonymous »

Ich habe die folgende Methode:

Code: Select all

public IEnumerable ToKeyValuePairs(object obj)
{
List keyValuePairs = new();

IEnumerable
 props = obj.GetType().GetProperties()
.Where(p => p.GetValue(obj, null) != null);

foreach (PropertyInfo p in props)
{
object value = p.GetValue(obj, null);
ICollection collection = value as ICollection;
if (collection != null)
{
AddRange(p.Name, ...???...)); // How to
// cast `ICollection collection` to `IEnumerable`?
}
else
{
keyValuePairs.Add(
new(p.Name, value.ToString()));
}
}

return keyValuePairs;
}
Dann habe ich eine andere Methode, die IEnumerable arrayElements akzeptiert:

Code: Select all

public List AddRange(
string keyName,
IEnumerable arrayElements)
{
// ... the code is omitted for the brevity
}
Meine Frage ist also, wie ich die ICollection-Sammlung umwandeln kann, um diesen Parameter zur Methode AddRange hinzuzufügen, die IEnumerable akzeptiert?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post