如何从库调用方法到 C# 控制台
我在新库中创建了一个方法 这是我的代码,
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;
}
}
}
}
}
- 我如何在控制台“program.cs”中调用该方法,
- 我收到一条错误,提示“错误 2 'ClassLibrary1.Class1.ISprime(int)':并非所有代码路径都返回值”,
这是什么意思?
抱歉,我是一名新程序员。
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;
}
}
}
}
}
- how can i call that method in my console " program.cs "
- 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1.) 通过执行以下操作来调用该方法:
或
2.) 您需要在该方法的最后返回一些值。我还改变了一些逻辑:
3.)回答有关逻辑不同之处的评论。尝试运行这个,你会看到差异。
1.) call the method by doing the following:
or
2.) You need to return some value at the very end of the method. I also changed some of the logic:
3.) Answering comment about what's different from the logic. Try running this and you'll see the differences.
将
return true
移至for
循环之后。尝试理解我为什么这么说:)
Move the
return true
to after thefor
loop.Try understand why I say that :)
这是一个编译错误,与从另一个程序调用它无关。基本上,通过所有的 if 和 else,有一条执行路径不会从函数返回值。
虽然您可以在方法末尾添加
return true
来满足编译器,你的逻辑也有缺陷,因为在内部(在循环中)否则,你返回 true,尽管它实际上可能不是素数。将
return true
移到循环之外,并删除循环中的 else 部分。要从另一个程序集/程序调用此方法,您必须引用此程序集并调用该方法。您也可以添加一条 using 语句。
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 thecompiler, 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.