Generic method multiple (OR) type constraint

前端 未结 4 603
无人及你
无人及你 2020-11-27 04:53

Reading this, I learned it was possible to allow a method to accept parameters of multiple types by making it a generic method. In the example, the following code is used wi

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 05:40

    If ChildClass means it is derived from ParentClass, you may just write the following to accept both ParentClass and ChildClass;

    public void test(string a, T arg) where T: ParentClass 
    {
        //do something
    }
    

    On the otherhand, if you want to use two different types with no inheritance relation between them, you should consider the types implementing the same interface;

    public interface ICommonInterface
    {
        string SomeCommonProperty { get; set; }
    }
    
    public class AA : ICommonInterface
    {
        public string SomeCommonProperty
        {
            get;set;
        }
    }
    
    public class BB : ICommonInterface
    {
        public string SomeCommonProperty
        {
            get;
            set;
        }
    }
    

    then you can write your generic function as;

    public void Test(string a, T arg) where T : ICommonInterface
    {
        //do something
    }
    

提交回复
热议问题