C# Passing a class type as a parameter

后端 未结 6 1638
清酒与你
清酒与你 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:43

    You need a generic:

    public void FillWsvcStructs(DataSet ds) where TBaz : IElementRequest, new()
    {
        // ...
        IElementRequest req = new TBaz();
        // ...
    }
    

    The generic constraint ("where...") enforces that the type you pass in implements the IElementRequest interface and that it has a parameter-less constructor.

    Assuming you had a class Baz similar to this:

    public class Baz : IElementRequest
    {
        public Baz()
        {
        }
    }
    

    You would invoke this method like so:

    DataSet ds = new DataSet();
    FillWsvcStructs(ds);
    

    Addendum

    Multiple, different, generic type parameters can each have there own type constraint:

    public void FillWsvcStructs(DataSet ds) 
        where TFoo : IFoo, new()
        where TBar : IBar, new()
        where TBaz : IElementRequest, new()
    {
        // ...
        IFoo foo = new TFoo();
        IBar bar = new TBar();
        IElementRequest req = new TBaz();
        // ...
    }
    

提交回复
热议问题