C# Return Different Types?

后端 未结 15 2082
无人及你
无人及你 2020-12-08 09:11

I got something like this:

public [What Here?] GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = ne         


        
15条回答
  •  旧时难觅i
    2020-12-08 09:58

    use the dynamic keyword as return type.

     private dynamic getValuesD()
        {
            if (typeof(T) == typeof(int))
            {
                return 0;
            }
            else if (typeof(T) == typeof(string))
            {
                return "";
            }
            else if (typeof(T) == typeof(double))
            {
                return 0;
            }
            else
            {
                return false;
            }
        }
    
            int res = getValuesD();
            string res1 = getValuesD();
            double res2 = getValuesD();
            bool res3 = getValuesD();
    

    // dynamic keyword is preferable to use in this case instead of an object type

    // because dynamic keyword keeps the underlying structure and data type so that // you can directly inspect and view the value.

    // in object type, you have to cast the object to a specific data type to view // the underlying value.

    regards,

    Abhijit

提交回复
热议问题