by Anonymous » 11 Jul 2025, 18:14
Ich habe eine generische Methode, die Typ t (generisches) zurückgibt. In der Methode, wenn t ein Array ist, möchte ich dieses Array mit Daten erstellen und bevölkern. Ich habe jetzt eine Liste von Objekten dieses Basistyps. Issue. Die angegebene Linie wird nicht kompilieren ("" Typ "Objekt" nicht konvertieren? [] 'Zu' t '"), aber letztendlich möchte ich erreichen.
Code: Select all
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Testing test = new Testing();
DataClass[] output = test.MyMethod();
}
public class DataClass
{
public int I = 0;
public DataClass()
{
}
}
public class Testing
{
public T MyMethod()
{
T result = default(T);
if (typeof(T).IsArray)
{
Type? baseType = typeof(T).GetInterfaces()
.Where(o => o.IsGenericType
&& o.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable))
.Select(o => o.GetGenericArguments()[0]).FirstOrDefault();
if (baseType != null)
{
List items = new List();
for (int i = 0; i < 5; i++)
{
// Just example code here to populate the array...
items.Add(Activator.CreateInstance(baseType));
}
result = (T)items.ToArray(); //
Ich habe eine generische Methode, die Typ t (generisches) zurückgibt. In der Methode, wenn t ein Array ist, möchte ich dieses Array mit Daten erstellen und bevölkern. Ich habe jetzt eine Liste von Objekten dieses Basistyps. Issue. Die angegebene Linie wird nicht kompilieren ("" Typ "Objekt" nicht konvertieren? [] 'Zu' t '"), aber letztendlich möchte ich erreichen.[code]static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Testing test = new Testing();
DataClass[] output = test.MyMethod();
}
public class DataClass
{
public int I = 0;
public DataClass()
{
}
}
public class Testing
{
public T MyMethod()
{
T result = default(T);
if (typeof(T).IsArray)
{
Type? baseType = typeof(T).GetInterfaces()
.Where(o => o.IsGenericType
&& o.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable))
.Select(o => o.GetGenericArguments()[0]).FirstOrDefault();
if (baseType != null)
{
List items = new List();
for (int i = 0; i < 5; i++)
{
// Just example code here to populate the array...
items.Add(Activator.CreateInstance(baseType));
}
result = (T)items.ToArray(); //