gpt4 book ai didi

C#:部分方法和操作,未实现的主体

转载 作者:行者123 更新时间:2023-11-30 22:42:20 25 4
gpt4 key购买 nike

我想从声明类的外部调用分部方法。这是不允许的,因为部分方法是隐式私有(private)的。您不能将委托(delegate)设置为指向部分,因此我提出以下建议:

  public partial class MyClass  {

AnotherClass _anotherClass;

public MyClass () {
_anotherClass = new AnotherClass();
_anotherClass.Method = new Action(() => {
this.Method();
});
}

partial void Method();

//sometimes this method will be implemented
//partial void Method() {
//do something
//}
}

public class AnotherClass {

public Action Method { get; set;}

public void SomeOtherMethod(){
this.Method();
}
}

这些类是紧耦合的,它们处于父子关系中。我希望 parent 有一个可以重写的方法来了解 child 的属性变化。我可以将事件处理程序附加到每个 child ,但是 child 已经知道其 parent ,因此让 child 直接通知 parent 似乎是可行的方法。除非 parent 不关心,这就是为什么我希望能够在我关心的情况下实现部分。这个问题基本上是关于编程的难易程度与性能的关系。我知道我只能将事件处理程序附加到我关心的情况,但是通过上面的实现,我可以生成所有部分方法,并且只在我关心的情况下实现部分方法。

我的问题与部分方法 Method() 未实现的时间有关。当调用 Action 方法时,编译器是否会优化它,因为它的主体是空的?如果我收到大量这些 Action 调用,我会遭受性能损失吗?有没有更好的方法来获得相同的功能?

最佳答案

根据 MSDN (强调):

One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.

因此,没有真正的惩罚,因为调用被优化掉了。

关于C#:部分方法和操作,未实现的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4466575/

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