C#为什么对象无法转换为int

时间:2013-08-16 17:49:21

标签: c#

我在运动时遇到一些问题..我必须编写一个程序,询问用户N的值,然后计算N!使用递归。 我写了类似的东西

 namespace ConsoleApplication19
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This program will calculate a factorial of random number. Please type a number");
            String inputText = Console.ReadLine();
            int N = int.Parse(inputText);

String outputText = "Factorial of " + N + "is: "; int result = Count(ref N); Console.WriteLine(outputText + result); Console.ReadKey(); } private static object Count(ref int N) { for (int N; N > 0; N++) { return (N * N++); } } }

问题在于“int result = Count(ref N);”我不知道为什么它不能转换为int。如果有人能帮助我,我将不胜感激。

3 个答案:

答案 0 :(得分:7)

因为它返回一个对象并且对象不能隐式转换为int,你可以做的就是更改方法的签名,如

private static int Count(ref int N)

或者你可以这样做

int result = (int)Count(ref N);

举一个简单的例子

//this is what you are doing
object obj = 1;
int test = obj;   //error cannot implicitly convert object to int. Are you missing a cast?

//this is what needs to be done
object obj = 1;
int test = (int)obj; //perfectly fine as now we are casting

// in this case it is perfectly fine other way around
obj = test;  //perfectly fine as well

答案 1 :(得分:0)

我想这是因为你的方法类型是“对象”,它应该是“intp>

答案 2 :(得分:-2)

是的,正如之前的回复所提到的,你不需要ref,你需要返回一个int。你的问题说你需要使用递归,但你正在使用for循环?

这是你如何写一个阶乘递归方法:

public long Factorial(int n)
{
   if (n == 0)  //base
     return 1;
   return n * Factorial(n - 1);
}