日期:2014-05-17  浏览次数:20934 次

c#中,部分方法为什么不能有返回值呢?
本帖最后由 AceHung 于 2011-01-05 13:22:37 编辑 正在看《c#入门经典》,在第十章提到部分方法不能有返回值,不是很明白,特此请教,谢谢!
ps :本人没任何编程基础,刚开始自学,如果问的问题有什么不妥之处,请不要见怪,谢谢!
------最佳解决方案--------------------
呵呵,我跟楼主一样都在自学,也看过C#入门经典,但是很多都看不明白,现在我在看C#图解教程和C#与.NET3.5高级程序设计,感觉非常不错,通俗易懂,我这里有电子版的,如果有需要就站内联系我,我发给你。感觉C#入门经典并不适合0基础的初学者。
------其他解决方案--------------------
你说的是void ?

------其他解决方案--------------------
举个例子,方法1:bool 我叫xxx去吃饭(饭的坐标){}

执行结果,xxx去吃了,吃完返回true,由于种种原因没吃,那返回false。

如果我根本不关心他吃饭成功了没有,那就有了方法2:void 我叫xxx去吃饭(饭的坐标){}

结果:吃完没吃完我不知道,但是确实叫他去吃了。
------其他解决方案--------------------
楼上的解释很形象。
------其他解决方案--------------------
如果你另外一个方法需要一个值!!比如说一个方法传进去2个参数 1 和 2,你这个方法是要把他们相加..而另外一个方法需要这个相加的值!你就需要返回一个Int
如果你的方法只是执行一下不需要值!比如说你这个方法需要显示一句话,你大可以Console.writeline("");不需要给他返回值!
不知道我有没有说明白!反正这个返不返回值 是你决定的  你想让他返回他就返回 不想让他返回就不返回 
------其他解决方案--------------------
lz说的是Partial Method吧

Partial Method要求必须是Private的,不能有返回值,参数不能是out的。不能用virtual , abstract , override , new , sealed , or extern修饰
------其他解决方案--------------------
贴下原文:

Partial classes may also define partial methods. Partial methods are defined in one partial class
definition without a method body, and implemented in another partial class definition. In both places,
the partial keyword is used:
public partial class MyClass
{
partial void MyPartialMethod();
}
public partial class MyClass
{
partial void MyPartialMethod()
{
// Method implementation
}
}
Partial methods can also be static, but they are always private and can ’ t have a return value. Any
parameters they use can ’ t be out parameters, although they can be ref parameters. They also can ’ t use
the virtual , abstract , override , new , sealed , or extern modifier.
Given these limitations, it is not immediately obvious what purpose partial methods fulfill. In fact, they
are important when it comes to code compilation, rather than usage. Consider the following code:
public partial class MyClass
{
partial void DoSomethingElse();
public void DoSomething()
{
Console.WriteLine(“DoSomething() execution started.”);
DoSomethingElse();
Console.WriteLine(“DoSomething() execution finished.”);
}
}
public partial class MyClass
{
partial void DoSomethingElse()
{
Console.WriteLine(“DoSomethingElse() called.”);
}
}

Here, the partial method DoSomethingElse is defined and called in the first partial class definition,
and implemented in the second. The output, when DoSomething is called from a console application, is