【问题标题】:Returning string and int from same method从同一方法返回字符串和 int
【发布时间】:2021-12-05 14:38:35
【问题描述】:
public static int getInfo(string info)
    {
        string inputValue;
        int infor;
        Console.WriteLine("Information of the employee: {0}", info);
        inputValue = Console.ReadLine();
        infor = int.Parse(inputValue);
        return infor;

    }

在上面的代码中,如何获取一个人的姓名(字符串)和薪水(整数)?规范是我需要调用该方法两次进行信息检索。

【问题讨论】:

  • 所以你想让你的方法返回一个字符串或一个整数?
  • 这说明了 XY 问题(如果您不知道这意味着什么,请用 Google 搜索;我在移动设备上没有方便的链接)。你想用这个来达到什么目的?
  • 谢谢你们。我通过在 main 方法中显式地将字符串转换为另一种方式。

标签: c#


【解决方案1】:

如果你创建一个包含信息和薪水的类,你可以单独传递它或更好地传递它

 public static int getInfo(string info,int salary)

或创建一个类,

 public class MyInfo
    {
        public int info { get; set; }
        public int salary { get; set; }

    }

方法签名如下,

 public static int getInfo(MyInfo info)

如果您想同时返回 string 和 int ,最好将方法签名更改为 type class MyInfo

 public static MyInfo getInfo(MyInfo info)

【讨论】:

  • 我认为 OP 希望他的方法返回信息。
  • @PieterWitvoet 可以按原样编辑。 2 更多在 c# 中获得金牌! :)
  • @Sajeetharan 2 更多金币!嫉妒的!祝你好运,你会很快搞定的
  • 我不能在这种特殊情况下使用这些类,因为规范说我需要调用两次方法并从一个方法中获取名称和薪水。
  • @PrashantBhandari 什么规格?谁建议的?
【解决方案2】:

你可以让它返回一个包含两个值的元组,如下所示:

internal Tuple<int, string> GetBoth(string info)
{
    string inputValue;
    int infor;
    Console.WriteLine("Information of the employee: {0}", info);
    inputValue = Console.ReadLine();
    infor = int.Parse(inputValue);
    return new Tuple<int, string>( infor, inputValue );
}

internal void MethodImCallingItFrom()
{
    var result = GetBoth( "something" );
    int theInt = result.Item1;
    string theString = result.Item2;
}

【讨论】:

    【解决方案3】:

    为了从一个方法返回多个值,我们可以使用元组或 (DataType, DataType,..)。

    元组是只读的。因此,只能在声明时通过构造函数进行赋值。

    以下示例使用多种数据类型作为返回类型。既可读写又可读写。

        public (string, int) Method()
        {
            (string, int) employee;
            employee.Item1="test";
            employee.Item2=40;
    
            return employee;
        }
    

    您可以在您的主代码中调用上述方法,如下所示:

        static void Main(string[] args)
        {
            
            (string name,int age) EmpDetails = new Program().Method();
            string empName= EmpDetails.name;
            int empAge = EmpDetails.age;
    
            //Not possible with Tuple<string,int>
            EmpDetails.name = "New Name";             
            EmpDetails.age =  41;
        }
    

    但是,最好的做法是使用具有属性的类,如上述答案中所述。

    【讨论】:

    • 我同意使用具有属性的类是最好的答案,但是大约 20 年前,当我刚刚弄清楚这一点时,我会喜欢这个(并且仍然喜欢)......这个答案比呜呜!!!
    【解决方案4】:
    public static void Main(string[] args)
        {
            string eName, totalSales;
            double gPay, tots, fed, sec, ret, tdec,thome;
            instructions();
            eName = getInfo("Name");
            totalSales = getInfo("TotalSales");
            tots = double.Parse(totalSales);
            gPay = totalGpay(tots);
    

    }

    public static string getInfo(string info)
        {
            string inputValue;
            Console.WriteLine("Information of the employee: {0}", info);
            inputValue = Console.ReadLine();
    
            return inputValue;
    
        }
    

    这是需要的。可以用你们提到的其他技巧来完成。无论如何,谢谢。

    【讨论】:

      【解决方案5】:

      为什么不直接返回一个大小为 2 的字符串数组呢?在第一个 (array[0]) 有字符串,在第二个 (array[0]) 有 int...

      public static string[] GetInfo (string info)
      

      希望我能正确理解你的问题^^

      【讨论】:

      • 我可以使用 TryParse 和 if else 来完成此操作,但情况是我需要调用该方法两次。 :(
      • 你也可以做'string stringname + Convert.ToString(int intname);'
      【解决方案6】:

      您需要创建一个人员类并读取姓名和薪水

      public class Person
      {
          public string Name {get; set;}
          public decimal Salary {get; set;}
      }
      

      你的功能将是:

      public static Person getInfo(string info)
      {
          string inputName;
          string inputSalary;
      
          Console.WriteLine("Information of the employee: {0}", info);
      
          Console.WriteLine("Name:");
          inputName = Console.ReadLine();
      
          Console.WriteLine("Salary:");
          inputSalary = Console.ReadLine();
      
          Person person = new Person();
          person.Name = inputName;
          person.Salary = int.Parse(inputSalary);
          return person;
      
      }
      

      【讨论】:

        【解决方案7】:

        如果你想要一种方法返回不同类型的信息,那么我会使用泛型:

        public static T GetInfo<T>(string name);
        
        // This can be called as following:
        string name = GetInfo<string>("name");
        int salary = GetInfo<int>("salary");
        

        但是有一个问题:Console.ReadLine 返回一个string,而我们的方法可以返回任何类型。它如何将字符串转换为其“目标”类型?您可以检查T 并为您想要支持的所有类型编写自定义逻辑,但这既麻烦又脆弱。更好的解决方案是让调用者传入一个知道如何将字符串转换为特定类型的小函数:

        public static T GetInfo<T>(string name, Func<string, T> convert);
        
        // This can be called as following:
        string name = GetInfo<string>("name", s => s);
        int salary = GetInfo<int>("salary", int.Parse);
        

        现在如何实现该方法?

        public static T GetInfo<T>(string name, Func<string, T> convert)
        {
            Console.WriteLine("Please enter " + name);
            string input = Console.ReadLine();
            return convert(input);
        }
        

        几点说明:

        • 类型参数通常只命名为T,但我发现给它们提供更具描述性的名称很有用,例如TInfo
        • &lt;string&gt;&lt;int&gt; 部分可以在第二个示例中省略,因为编译器有足够的信息来推断它们的类型。
        • 我保留了错误处理以使示例简短明了。不过,在生产代码中,您需要想出一种策略来处理无效输入。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-19
          • 1970-01-01
          • 1970-01-01
          • 2013-01-03
          • 1970-01-01
          • 2022-01-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多