How can i call a method from library to C# console

Deadly 提交于 2019-12-10 18:43:26

问题


i created a method in a new library this is my code

namespace ClassLibrary1
{
    public class Class1
    {
        public static bool ISprime(int prime)
        {

            if (prime < 2)
                return false;
            else if (prime == 2)
                return true;
            else
            {
                for (int i = 2; i < prime; i++)
                {
                    if (prime % i == 0)
                        return false;
                    else
                        return true;
                }

            }
        }
    }
}
  1. how can i call that method in my console " program.cs "
  2. i got an error that said " Error 2 'ClassLibrary1.Class1.ISprime(int)': not all code paths return a value"

what does that mean ?

sorry i'm a new programmer.


回答1:


1.) call the method by doing the following:

ClassLibrary1.Class1.ISprime(123);

or

Class1.ISprime(123);  // make sure to reference ClassLibrary1 at the top of your class

2.) You need to return some value at the very end of the method. I also changed some of the logic:

public static bool ISprime(int prime)
{
    if (prime == 1) 
        return false;
    if (prime == 2) 
        return true;

    for (int i = 2; i < Math.Sqrt(prime); ++i)  {
        if (prime % i == 0) 
            return false;
    }

    return true;
}

3.) Answering comment about what's different from the logic. Try running this and you'll see the differences.

    for (int n = -10; n < 10; n++)
    {
        if (Class1.IsPrimeCorrect(n) != Class1.IsPrimeIncorrect(n))
        {
            Console.WriteLine(n);
        }
    }



回答2:


Move the return true to after the for loop.

Try understand why I say that :)




回答3:


This is a compilation error and unrelated to calling it from another program. Basically , through all the if's and the else's, there is a path of execution that does not return a value from the function.

While you can add a return true at the end of your method to satisfy the compiler, your logic is also flawed because in the inner (in the loop) else, you are returning true, eventhough it might actually not turn out to be prime. Move the return true outside the loop and remove the else part in the loop.

To call this from another assembly / program, you have to reference this assembly and call the method. You may add a using statement too.



来源:https://stackoverflow.com/questions/9389870/how-can-i-call-a-method-from-library-to-c-sharp-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!