Class type reflection

I want to somehow pass the type of the class as a parameter to a method. Something like that

public void DoWork<TClass>(int time)
{
     IJobDetail job = JobBuilder.Create<TClass>()
                .WithIdentity("job1", "group1")
                .Build();
}

Is it possible to get classtype as a parameter or somehow get the type of a class by reflecting an object of this type?

UPDATE 1: I just tried using a generic type and got this error

`The type TClass cannot be used as type parameter T in the generic type or method quartz.jobbuilder.create<T>().  There is now boxing conversion or type parameter conversion from tclass to quartz.ijob`

Create MEthod of Quartz

// Summary:
    //     Create a JobBuilder with which to define a Quartz.IJobDetail, and set the
    //     class name of the job to be executed.
    //
    // Returns:
    //     a new JobBuilder
    public static JobBuilder Create<T>() where T : IJob;
+3
source share
2 answers

You are probably looking for a generic function - this allows your function to specify a type parameter:

public void DoWork<TClass>(int time)
    where TClass : quartz.ijob
{
    IJobDetail job = JobBuilder.Create<TClass>()
        .WithIdentity("job1", "group1")
        .Build();
}

Edit

You can also set a restriction on the type parameter that seems to be required here. Use the syntax where TClass : quartz.ijob.

Edit # 2

, . , :

DoWork<SomeClassType>(123);

, , . , :

public void DoWork<TClass>(int time, TClass instance)
    where TClass : quartz.ijob

:

var myInstance = new SomeClassType();  // SomeClassType must inherit quartz.ijob
DoWork(123, myInstance);

, myInstance , . , , , :

function SomethingOrOther(object instance)
{
    DoWork(123, instance);   // will not compile, as the compiler doesn't know the type of "instance"
}

DoWork , (. MakeGenericMethod). , . (.. ) .

+2

, .

typeof(YourClassHere) yourObject.GetType().

acitvator: Activator.CreateInstance(type, parameters for constructor)

EDIT , .

public void DoWork<TClass>(int time)
{
     IJobDetail job = (IJobDetail) Activator.CreateInstance(typeof(TClass), null /* no parameters */);
                job.WithIdentity("job1", "group1");
                job.Build();
}
0

All Articles