Let method take any data type in c#

后端 未结 6 1427
栀梦
栀梦 2020-12-08 04:29

I have a lot of unit tests that pretty much tests the same behavior. However, data type changes.

I am trying to create a generic method that can take any data type.

6条回答
  •  醉酒成梦
    2020-12-08 05:20

    void MyTestMethod(T t) { }
    

    gets you a generic test method, but I can't imagine any way that could be useful. What do you need to test? How do you know type T has those methods? T can be any type in the above method. The only methods you can call from t in the above example are the common methods of object.

    What you really need to do is identify a common behaviour against one or more types which you want to test, and define the syntactical contract of that behaviour through an interface. You can then constrain your generic test method to only accept types which implement that interface.

    interface IMyInterface
    {
        void DoSomething();
    } 
    
    void MyTestMethod(T t) where T : IMyInterface
    { 
        t.DoSomething();
    }
    

提交回复
热议问题