将类类型作为参数传递

将类类型作为参数传递

这是C#吗?
Passing Class type as a parameter

我有一个实现接口(interface)的类适配器。我想用MyFooClass实例填充数组结构,其中MyFooClass的名称或引用是我希望从外部接收的。我将在我的适配器代码中实例化它们。

例如:

    public void FillWsvcStructs(DataSet ds, ClassType Baz)
    {
        IFoo.Request = ds.DataTable[0].Request;
        IFoo.Modulebq = string.Empty;
        IFoo.Clasific = string.Empty;
        IFoo.Asignadoa = ds.DataTable[0].Referer;
        IFoo.Solicita = "Jean Paul Goitier";


        // Go with sub-Elems (Also "Interfaceated")
        foreach (DataSet.DataTableRow ar in ds.DataTable[1])
        {
            if ((int) ar.StatusOT != (int)Props.StatusOT.NotOT)
            {
                ///From HERE!
                IElemRequest req = new (Baz)(); // I don't know how to do it here
                ///To HERE!

                req.Id = string.Empty;
                req.Type = string.Empty;
                req.Num = string.Empty;
                req.Message = string.Empty;
                req.Trkorr = ar[1];
                TRequest.Add(req);
            }
        }
    }

最佳答案

我相信Genericstheir constraints应该做您想要的事情:

public void FillWsvcStructs<ClassType>(DataSet ds) where ClassType : IElemRequest, new()
{
    IFoo.Request = ds.DataTable[0].Request;
    IFoo.Modulebq = string.Empty;
    IFoo.Clasific = string.Empty;
    IFoo.Asignadoa = ds.DataTable[0].Referer;
    IFoo.Solicita = "Jean Paul Goitier";


    // Go with sub-Elems (Also "Interfaceated")
    foreach (DataSet.DataTableRow ar in ds.DataTable[1])
    {
        if ((int) ar.StatusOT != (int)Props.StatusOT.NotOT)
        {
            IElemRequest req = new ClassType();

            req.Id = string.Empty;
            req.Type = string.Empty;
            req.Num = string.Empty;
            req.Message = string.Empty;
            req.Trkorr = ar[1];
            TRequest.Add(req);
        }
    }
}

关于C#将类类型作为参数传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10903452/

10-11 02:24