Let method take any data type in c#

后端 未结 6 1418
栀梦
栀梦 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:15

    Make your parameter type "object" and your method will accept every type as input. Then you can detect its type using GetType(), and even use tools like int.Parse, ToString(), and type casting to convert your input to a specific type and then work with it.

        static void whatsmytype(object place)  // Will accept any type
        {
            Type t = place.GetType(); // detects type of "place" object
            if (t.Equals(typeof(string)))
                Console.WriteLine("Type is string.");
            else if (t.Equals(typeof(int)))
                Console.WriteLine("Type is int.");
            else 
                Console.WriteLine("Type is unknown.");
        }
    

    Edit: If readability is not really an issue, you could replace the method declaration line with code below, to get a minor speed improvement:

            static void whatsmytype(T place)
    

提交回复
热议问题