【问题标题】:How can I change a method's return type based on an argument value?如何根据参数值更改方法的返回类型?
【发布时间】:2017-12-09 00:29:15
【问题描述】:

如何根据 returnType 的值更改此方法的返回类型? 我想返回整数、浮点数和小数,而不为每一个创建单独的方法。具体来说,如何根据returnType的值改变第一行的decimal??

public static decimal RequestNumber(string returnType)
    {
        Console.WriteLine(inputRequest);

        decimal result;

        switch(returnType)
        case decimal:
            bool parsed = decimal.TryParse(Console.ReadLine(), out result);
        case int:
            bool parsed = int.TryParse(Console.ReadLine(), out result);
        case single:
            bool parsed = single.TryParse(Console.ReadLine(), out result);
        return result;
    }

任何帮助将不胜感激!

【问题讨论】:

  • 最好开始研究如何使用ConvertTo 方法或将类型更改为Int 并传入一个小数作为输入参数.. 你需要返回阅读C# Basics跨度>
  • 似乎是重复的,但它确实使用输入参数为其添加了旋转:stackoverflow.com/questions/20705643/…
  • 尝试使用泛型方法返回 T 并为检测到的每个字符串类型返回 Func

标签: c#


【解决方案1】:

您可以使用对象类型,然后在调用时强制转换返回结果;

private static object duo(string req)
{

    if (req == "Y")
    {
        string s = "Type String";
        return s;
    }
    else
    {
        List < string > l  = new List<string> { "Type", "List" };

        return l;
    }
}

然后使用它:

List<string> res = (List<string>)duo("H");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多