简体   繁体   中英

Convert object to generic T

How can I pass the T by parameter but I need to do something like this:

Added: I need to create one thread for each SqlServerTable object, and it is a Datatable, but into my method CheckChanges my datatable is converted to my objects inherited from IHasId

 > class Account: IHasId<int> > class Requisition: IHasId<int> > class EtcEtc: IHasId<int> 

I need to pass those classes type by parameter such as: tableItem.TableType

and below I pass the T from that, I can't pass the T when I call the method because It comes from a object parameter dinamically

public static void Start()
{
    SqlServerTables.ForEach(tableItem =>
    {
        T t = (T)tableItem.TableType; // <- THIS IS WHAT I NEED WORKING.. :(
        var destinationTable = SqlServerDb.LoadDestination(tableItem.Table.TableName, tableItem.Table.PrimaryKey[0].ColumnName, false);
        // HOW CAN I GET THE <T> below?
        var thread = new Thread(() => SincronizeTable<T>(destinationTable)) { Name = tableItem.Table.TableName };
        thread.Start();
    });
}

private static void SincronizeTable<T>(DataTable sqlServerTable)
{
    var tableName = sqlServerTable.TableName;
    var primaryKey = sqlServerTable.PrimaryKey[0].ColumnName;

    while (_isAlive)
    {
        var sourceTable = TaskDb.LoadDataFromTask(tableName, primaryKey, true, false);
        var destinationTable = SqlServerDb.LoadDestination(tableName, primaryKey, false);

        var differences = Migration.CheckChanges<T>(sourceTable, destinationTable, false, primaryKey);

        // Save changes
        var success = Migration.SaveChanges(differences, tableName, primaryKey, Program.ArgumentParams.BatchUpdateQuantity);

        Thread.Sleep(1000);
    }
}
}

It sounds like you want to dynamically call a generic method.

Here's how:

Starting with a simple type:

public class Foo
{
}

And a simple method in a class:

public class Bar
{
    public void DoSomething<T>()
    {
        Console.WriteLine(typeof(T).FullName);
    }
}

Then you can call it this way:

Foo foo = new Foo();

Type type = foo.GetType();

Bar bar = new Bar();

bar
    .GetType()
    .GetMethod("DoSomething")
    .MakeGenericMethod(type)
    .Invoke(bar, null);

It seems that you want to supply T to a generic method.

public void MyMethod<T>(Class1 myClass)
{
}

Instead of requiring the type declaration, you can derive it by passing the type.

public void MyMethod<T>(Class1 myClass, T someClass)
{
}

If you only have the type and not an instance of the type, then this is a duplicate of Calling generic method with a type argument known only at execution time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM