gpt4 book ai didi

c# - C# 解释中的部分方法

转载 作者:可可西里 更新时间:2023-11-01 08:18:42 24 4
gpt4 key购买 nike

我很难理解部分方法的用法。

您能否提供一个与 LINQ 或类似数据库无关的示例?

部分方法是否与我们在 WinForms 中并在它后面编码时一样,如果我们使用一个方法,它会被编译,但如果我们不使用,它就会被编译器删除?对吗?

最佳答案

当你有一个分部类时,你可以在一个文件中定义方法的签名并在另一个文件中实现。那是一种部分方法。

所以在一个文件中你有:

partial class Foo
{
partial void Bar(); // no implementation

public void DoSomething()
{
// do some stuff...
Bar(); // this will be removed if Bar isn't implemented in another partial class
// do something else...
}
}

在另一个你有

partial class Foo
{
partial void Bar()
{
// do something...
}
}

这让第一个文件调用 Bar 而不必担心 Bar 是否被实现。如果 Bar 没有在某处实现,那么对它的调用将被删除(来自 here ):

Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.

部分方法必须返回 void,否则如果该方法未实现,则删除所有方法调用是不安全的:

Partial method declarations must begin with the contextual keyword partial and the method must return void.

与部分类一样,主要用途是处理生成的代码:

Partial methods are especially useful as a way to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.

因此,您可能已经生成了调用分部方法的代码(在生成的代码中定义而没有实现),并且您可以自由扩展该分部类并在需要/需要时实现该分部方法。

关于c# - C# 解释中的部分方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com