C# 阶级类型的反思

C# 阶级类型的反思,c#,reflection,quartz-scheduler,C#,Reflection,Quartz Scheduler,我想了解如何将类类型作为参数传递到方法中。像这样的 public void DoWork<TClass>(int time) { IJobDetail job = JobBuilder.Create<TClass>() .WithIdentity("job1", "group1") .Build(); } public void DoWork(整数时间) { IJobDetail job=JobB

我想了解如何将类类型作为参数传递到方法中。像这样的

public void DoWork<TClass>(int time)
{
     IJobDetail job = JobBuilder.Create<TClass>()
                .WithIdentity("job1", "group1")
                .Build();
}
public void DoWork(整数时间)
{
IJobDetail job=JobBuilder.Create()
.WithIdentity(“工作1”、“组1”)
.Build();
}
是否可以将类类型作为参数获取,或者通过反射该类型的对象以某种方式获取类类型

更新1: 我只是尝试使用泛型类型,但收到了此错误

`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`
`类型TClass不能用作泛型类型或方法quartz.jobbuilder.create()中的类型参数T。现在有从tclass到quartz.ijob的装箱转换或类型参数转换`
石英的制作方法

// 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;
//摘要:
//创建用于定义Quartz.IJobDetail的作业生成器,并设置
//要执行的作业的类名。
//
//返回:
//新来的工人
公共静态作业生成器Create(),其中T:IJob;

您可能正在寻找一个函数——这允许您的函数指定一个类型参数:

public void DoWork<TClass>(int time)
    where TClass : quartz.ijob
{
    IJobDetail job = JobBuilder.Create<TClass>()
        .WithIdentity("job1", "group1")
        .Build();
}
但是,如果方法的签名包含泛型类型的参数,则编译器可以使用该参数推断类型。因此,如果签名是:

public void DoWork<TClass>(int time, TClass instance)
    where TClass : quartz.ijob
如上所述,
myInstance
的类型在编译时是已知的,因此编译器可以推断泛型类型。但是,如果您的类型实例为,则直到运行时才知道该类型,并且编译器无法帮助您:

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

在这种情况下,可以通过使用反射调用
DoWork
(请参阅)。然而,这种在泛型上使用反射的方法变得复杂、快速。它还违背了泛型的目的(即编译时安全性),通常表示存在设计缺陷。

一般来说,是的

您可以使用
typeof(yourclassehere)
获取类的类型,或者使用
yourObject.GetType()获取对象的类型

然后您可以使用acitvator轻松创建对象:
Activator.CreateInstance(类型,构造函数的参数)

问题编辑后编辑 如果你有通用的,那就更容易了

public void DoWork<TClass>(int time)
{
     IJobDetail job = (IJobDetail) Activator.CreateInstance(typeof(TClass), null /* no parameters */);
                job.WithIdentity("job1", "group1");
                job.Build();
}
public void DoWork(整数时间)
{
IJobDetail作业=(IJobDetail)Activator.CreateInstance(typeof(TClass),null/*无参数*/);
职务。具有身份(“职务1”、“组1”);
job.Build();
}

你能展示一下
Create
方法的定义吗?我把它放在了我的原始帖子中。这似乎可以修复错误,我还没有测试过它,我会在测试后报告。
function SomethingOrOther(object instance)
{
    DoWork(123, instance);   // will not compile, as the compiler doesn't know the type of "instance"
}
public void DoWork<TClass>(int time)
{
     IJobDetail job = (IJobDetail) Activator.CreateInstance(typeof(TClass), null /* no parameters */);
                job.WithIdentity("job1", "group1");
                job.Build();
}