How can I determine if an object can ToString into value or type name?

后端 未结 6 1706
青春惊慌失措
青春惊慌失措 2021-01-19 09:38

I am writing an interop between a php service and our crm. One of the things I need to do is make sure that simple types get converted ToString() for use later in a json co

6条回答
  •  醉梦人生
    2021-01-19 10:07

    I Think this is what you are looking, in the GetMethod the second argument is an empty array to watch for the .ToString(), just convert the i.GetType().GetMethod("ToString", new Type[] { }).DeclaringType == typeof(object) to a function and there you go.

    class Program
        {
            static void Main(string[] args)
            {
                int i = 55;
                var s = "some string";
                var x = new List();
                Console.WriteLine(i.ToString());
                Console.WriteLine(i.GetType().GetMethod("ToString", new Type[] { }).DeclaringType == typeof(object));
                Console.WriteLine(s.ToString());
                Console.WriteLine(s.GetType().GetMethod("ToString",new Type[]{}).DeclaringType == typeof(object));
                Console.WriteLine(x.ToString());
                Console.WriteLine(x.GetType().GetMethod("ToString",new Type[]{}).DeclaringType == typeof(object));
            }
        }
    

提交回复
热议问题