猿问

我已经发送了 2 个通用参数,第一个是 char,第二个是 int 为什么第一个如果

我已经向 func 发送了两个通用参数,并简单地询问它们是否是 int 类型,我将其中一个作为 char 发送,第二个作为 int 发送,但仍然 if cindison is work exsample :结果是第一个 if cond is work我真的不明白为什么因为第一个 arg 是 char


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApp5

{

    class Program

    {


        public static T Adds<T>(T number1 , T number2 )

        {

            if ((number1 is int) && (number2 is int))

            {

                Console.WriteLine("int test");

            }

            else if (number1 is double )

            {

                Console.WriteLine("double test");

            }

            return number1;

        }


        public static void Main(string[] args)

        {


            Console.WriteLine(Adds('c',2));

        }

    }

}


泛舟湖上清波郎朗
浏览 177回答 3
3回答

潇潇雨雨

这是你想要做的:class Program{&nbsp; &nbsp; public static T Adds<T>(object number1, object number2)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ((number1 is int) && (number2 is int))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("int test");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else if (number1 is double)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("double test");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return (T)Convert.ChangeType(number1, typeof(T));&nbsp; &nbsp; }&nbsp; &nbsp; public static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(Adds<int>('c', 2));&nbsp; &nbsp; }}

慕尼黑5688855

当前签名&nbsp;T Adds<T>(T number1, T number2)确保两个参数number1和number2必须是相同的类型。这就是为什么&nbsp;Add('c', 2)&nbsp;Add(1, 3.14)将被执行为&nbsp;Add<int>((int)'c', 2);&nbsp;Add<double>((double)1, 3.14);因为char可以隐式转换为int并且(第二个示例)int可以 隐式转换为double. 如果你想用自己的类型来对待每个参数,试试// T1 Adds<T1, T2>: if Adds return 1st parameter// T2 Adds<T1, T2>: if Adds return 2nd parameter&nbsp;T1 Adds<T1, T2>(T1 number1, T2 number2) {&nbsp; ...}在这种情况下Add('c', 2)将被称为// No conversion: T1 is char, T2 is intAdd<char, int>('c', 2)

一只甜甜圈

您已使用单个泛型类型声明了该方法。如果您希望参数具有单独的类型,则必须声明public&nbsp;static&nbsp;T&nbsp;Adds<T,T2>(T&nbsp;number1&nbsp;,&nbsp;T2&nbsp;number2&nbsp;)
随时随地看视频慕课网APP
我要回答