C# Passing a class type as a parameter

后端 未结 6 1639
清酒与你
清酒与你 2021-02-10 00:49

This for C#? Passing Class type as a parameter

I have a class adapter that implements an Interface. I want to fill an array structure with MyFooClass instances where M

6条回答
  •  独厮守ぢ
    2021-02-10 01:40

    That's probably best solved by using generics:

    public void FillWsvcStructs(DataSet ds) where T : IElemRequest, new()
    {
       //..
       //new() constraint enables using default constructor     
       IElemRequest req = new T(); 
       //IElemRequest constraint enables using interface properties
       req.Id = string.Empty;
       //..
     }
    

    If you have multiple types that you need to be able to access/instantiate, the declaration follows the same rules (as may easily be gathered from msdn):

    public void FillWsvcStructs() where T : IElemRequest, new() 
                                           where U : IFoo, new()
                                           where V : IBar, new()
    {
    
        //..
    }
    

提交回复
热议问题